Compare commits

...

266 Commits

Author SHA1 Message Date
TEC 438e2568be
---END PERSONAL NOPUSH DIVIDER---
--
2.42.0
2024-04-01 19:50:45 +08:00
TEC 8071b6e4c0
NOPUSH org: Don't fill displayed equations in text
* list/org.el (org-fill-element): If a displayed equation (\[ ... \])
starts on its own line, it should not be filled into the rest of the
text. I.e.,

some nice text
\[
  1+1=2
\]
more text.

should not become,

some nice text \[ 1+1=3 \] more text.

While the above example may not look bad, with non-trivial equations
this can become quite messy.
2024-04-01 19:50:45 +08:00
TEC 1947dc2f7b
NOPUSH org-src: Prettify inline results
* lisp/org.el (org-inline-src-prettify-results):

* lisp/org-src.el (org-fontify-inline-src-blocks-1):
2024-04-01 19:50:45 +08:00
TEC b47642f008
---NOPUSH PERSONAL DIVIDER---
--
2.42.0
2024-04-01 19:50:45 +08:00
TEC 16d76afc08
ox-latex: Fix interning of engraved theme keyword
* lisp/ox-latex.el (org-latex-src-block--engraved,
org-latex-inline-src-block--engraved): The engrave-faces backend expects
themes to be named using symbols, as does the default theme used by org
`org-latex-engraved-theme'. However, when set using #+attr_latex or the
use of #+latex_engraved_theme the value in the info plist is a string.
Thus, the code path needs to handle both string and symbol values,
interning string values to symbols.
2024-04-01 19:50:45 +08:00
TEC 69bddeb95e
ox-latex: Introduce \codefont command
* lisp/ox-latex.el (org-latex-engraved-preamble): Make it easier to
customise the font used in engraved Code environments with a \codefont
command (defaulting to \footnotesize).
2024-04-01 19:50:45 +08:00
TEC b4496e1c75
ox-latex: Use more robust engraved theme grouping
* lisp/ox-latex.el (org-latex-src--engrave-code): Use of curly brackets
for grouping has a few edge-cases which \begingroup-\endgroup should not
suffer from.
2024-04-01 19:50:45 +08:00
TEC 4d4324719a
ox-latex: Better handle multiple engraved themes
* lisp/ox-latex.el (org-latex-generate-engraved-preamble): Improve the
generated LaTeX code in the multiple-themes case. Using "\long\def"
instead of "\newcommand" mixed with "\renewcommand" is needed without
without duplicating the default theme.  The "\efstrut" command also
needs to be extracted out of the theme-generated commands, which was
previously overlooked.
2024-04-01 19:50:45 +08:00
TEC a1b107534d
ox-latex: Fix engraved-theme propagation
* lisp/ox-latex.el (org-latex-src-block--engraved,
org-latex-src--engrave-code, org-latex-inline-src-block--engraved):
Actually propagate the ":latex-engraved-theme" property through to the
`org-latex-src--engrave-code` call.  To account for whether the theme is
the default theme, or whether it will need to be explicitly switched to,
a new indicator argument ("explicit-theme-p") has been added to
`org-latex-src--engrave-code`.
2024-04-01 19:50:45 +08:00
TEC 80bb7a7059
ol: more versatile #+link replacement forms (WIP)
* lisp/ol.el (org-link-expand-abbrev, org-link--abbrev-functions): Allow
link abbreviations to use %s and %h as format-specs, as well as allowing
an anonymous function form with %(sexpr using tag).
2024-04-01 19:50:45 +08:00
TEC 2af808e7a5
org: Introduce semantic seperator fontification
* lisp/org.el (org-fontify-semantic-seperator,
org-set-font-lock-defaults): TODO
2024-04-01 19:50:45 +08:00
TEC 76b37c67a5
ox-html: Fix C++ label CSS
* lisp/ox-html.el (org-html-style-default): The "C++" pre-label works if
the "+" characters are backslash-escaped.
2024-04-01 19:50:45 +08:00
TEC 2ffdd6769c
---PATCH SET DIVIDER---
--
2.42.0
2024-04-01 19:50:45 +08:00
TEC 20a3bb0b34
org-latex-preview: Add authors header
* lisp/org-latex-preview.el: Mention that Karthik and I authored this
file.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur be43e34e3c
org-latex-preview: Fix bug when checking previews
*
lisp/org-latex-preview.el (org-latex-preview--check-all-fragments-produced):
When the first fragment in a preview run silently fails to render,
this function tries to cache a nil value as a fragment.  Fix by
checking that the fragment that fails to render is valid as a
fragment.
2024-04-01 19:50:45 +08:00
TEC e21e2b93b8
org-latex-preview: Take advantage of dvisvgm3.2
* lisp/org-latex-preview.el (org-latex-preview--tex-styled,
org-latex-preview--dvisvgm-filter,
org-latex-preview--dvisvgm-version>=3.1,
org-latex-preview-process-alist,
org-latex-preview--dvisvgm3-minor-version): Take advantage of the new
--message flag of dvisvgm 3.2 to produce a more concise output.
2024-04-01 19:50:45 +08:00
TEC 7e49b1fcf0
ox-html: Allow inlining svg tex as <svg> elements
* lisp/ox-html.el (org-html-latex-image--data, org-html-latex-image):
Add support for inlining dvisvgm-exported svgs as <svg> elements,
preserving the effect of the currentColor attribute.  While making this
change, we improve a few other aspects of the html LaTeX fragment export
system, namely refactoring/code style improvements and the recognition
of \[...\] and $$...$$ fragments as blocks not inline fragments.
2024-04-01 19:50:45 +08:00
TEC f8e95d47e9
org-latex-preview: Skip blank fragments
* lisp/org-latex-preview.el (org-latex-preview--construct-entries,
org-latex-preview-auto--regenerate-overlay): Blank fragments produce
invisible previews, which is at best silly and at worst confusing.  It's
much better to simply not produce a preview image of blank fragments.
We also now avoid exessive re-numbering calculations when repeatadly
generating live previews.
2024-04-01 19:50:45 +08:00
TEC a46e51ecfb
org-latex-preview: Accommodate a flaky cache
* lisp/org-latex-preview.el (org-latex-preview--get-cached): When using
persist, occasionally we need to be more careful about assuming that
cache entries exist.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 70e36ff4c3
org-latex-preview: Handle html export preview fail
* lisp/org-latex-preview.el (org-latex-preview--check-all-fragments-produced):
This function assumes that previews are being generated for placement in
the buffer.  Handle the case of preview generation for HTML exports.
2024-04-01 19:50:45 +08:00
TEC bd13ef935e
org-latex-preview: Fix face selection Emacs 28 bug
* lisp/org-latex-preview.el (org-latex-preview--face-around): On Emacs
28 (and presumably below), should a face with :extend set be identified
as appropriate, the overlay may cast a pall (background colour) over the
rest of the line.  This can be addressed by replacing the use of the
default face to normalise display with an anonymous face that inherits
from default and has the :extend attribute set.

Reported-by: Roshan Shariff <roshan.shariff@gmail.com>
Link: https://list.orgmode.org/CAG8iPGxoAD7qmKzDXQ_SRFbmxD7jdM96piCa-dCSCpzae4rCsw@mail.gmail.com
2024-04-01 19:50:45 +08:00
TEC a44b22e77e
ox-html: Support for customised latex image dir
* lisp/ox-html.el (org-html-latex-image, org-html-prepare-latex-images,
org-html-latex-image-options): Allow for customising the LaTex image
directory in `org-html-latex-image-options'.
2024-04-01 19:50:45 +08:00
TEC 5b403f35f1
org-latex-preview: Rework general cache variable
* lisp/org-latex-preview.el (org-latex-preview--get-cached,
org-latex-preview--table, org-latex-preview-persist,
org-latex-preview-cache): Rename and tweak `org-latex-preview-persist'
to also allow for caching to a custom directory, and (in the near
future) unify behaviour with HTML export.

* testing/lisp/test-org-latex-preview.el: Accommodate for the cache variable
change.

* etc/ORG-NEWS: Accommodate for the cache variable change.
2024-04-01 19:50:45 +08:00
TEC 14c6d2d629
org-latex-preview: Add ignored auto environments
* lisp/org-latex-preview.el (org-latex-preview-live--src-buffer-setup,
org-latex-preview-auto--maybe-track-element-here,
org-latex-preview-auto-ignored-environments): Introduce a new
customisation variable `org-latex-preview-auto-ignored-environments',
for specifying environments that should not be automatically previewed.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 548ef5c51e
org-latex-preview: Dynamic throttle for live previews
* lisp/org-latex-preview.el (org-latex-preview-live--throttle,
org-latex-preview-live-throttle,
org-latex-preview-live--preview-times,
org-latex-preview-live--update-times,
org-latex-preview-live--record-hook,
org-latex-preview-live--regenerate,
org-latex-preview-live--update-props,
org-latex-preview-live--src-buffer-setup,
org-latex-preview-live--setup, org-latex-preview-live--teardown,
org-latex-preview--create-image-async): Find the optimal throttle
time for live preview updates dynamically.  The variable
`org-latex-preview-live--preview-times' records the last three
process run times, and `org-latex-preview-live-throttle' is set to
the average of these.  This ensures that there are never more than
two concurrent processes live-previewing a single fragment.  Start
another preview run process the end of the throttle period if the
preview image is out of date to ensure that the state of the
preview is eventually consistent with the contents of the
fragment.
2024-04-01 19:50:45 +08:00
TEC 16969e41a6
org-latex-preview: Adjust customisation scheme
* lisp/org-latex-preview.el (org-latex-preview-live--teardown,
org-latex-preview-live--setup, org-latex-preview-live--src-buffer-setup,
org-latex-preview-live--ensure-overlay, org-latex-preview-throttle,
org-latex-preview-debounce, org-latex-preview-live-preview-inline,
org-latex-preview-auto--open-this-overlay,
org-latex-preview-auto--detect-fragments-in-change,
org-latex-preview-auto--handle-post-cursor,
org-latex-preview--face-around, org-latex-preview-auto-generate,
org-latex-preview-auto-blacklist, org-latex-preview-clear-cache,
org-latex-preview--latex-preview-filter,
org-latex-preview--create-tex-file,
org-latex-preview--create-image-async, org-latex-preview--hash,
org-latex-preview--auto-aware-toggle, org-latex-preview--preview-region,
org-latex-preview-live--teardown, org-latex-preview-live--setup,
org-latex-preview-live--src-buffer-setup,
org-latex-preview-live--ensure-overlay,
org-latex-preview-auto--regenerate-overlay,
org-latex-preview-auto--close-previous-overlay,
org-latex-preview-auto--open-this-overlay,
org-latex-preview-auto--detect-fragments-in-change,
org-latex-preview--update-overlay,
org-latex-preview--indicate-processing, org-latex-preview-precompile,
org-latex-preview-open-functions, org-latex-preview-close-functions,
org-latex-preview-update-overlay-functions,
org-latex-preview-auto-command-blacklist,
org-latex-preview-processing-indicator,
org-latex-preview-default-process): Change the customisation naming
scheme to be more consistent.

* testing/lisp/test-org-latex-preview.el: Change the LaTeX preview
customisation naming scheme to be more consistent.

* lisp/org-compat.el: Change the LaTeX preview customisation naming
scheme to be more consistent.

* etc/ORG-NEWS: Change the LaTeX preview customisation naming scheme to
be more consistent.

* doc/org-manual.org (Footnotes, Previewing LaTeX fragments): Change the
LaTeX preview customisation naming scheme to be more consistent.
2024-04-01 19:50:45 +08:00
TEC 1b28fdaf7e
org-latex-preview: Formatting and spacing tweaks
* lisp/org-latex-preview.el (org-latex-preview--dvipng-filter,
org-latex-preview--latex-preview-filter,
org-latex-preview--create-tex-file,
org-latex-preview--create-image-async,
org-latex-preview--get-numbered-environments,
org-latex-preview-live--setup,
org-latex-preview-live--update-overlay-run,
org-latex-preview-auto--detect-fragments-in-change,
org-latex-preview--update-overlay): Adjust formatting/spacing.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur d6e8fadaab
org-latex-preview: Live previews in org-src bufs
* lisp/org-latex-preview.el (org-latex-preview-live--src-buffer-setup):
When live previews are enabled in an Org buffer and using org-src
buffers to edit LaTeX fragments (via `org-edit-special'), show
continuously updated previews in the source Org buffer if it is
visible.  If it is not visible, show continuously updated previews
in the org-src buffer.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur e275101d40
org-latex-preview: Eldoc support for live previews
* lisp/org-latex-preview.el (org-latex-preview-live-display-type,
org-latex-preview-live--display-in-eldoc,
org-latex-preview-live--update-eldoc,
org-latex-preview-live--setup, org-latex-preview-live--teardown):
Add Eldoc support for live previews.  The user option
`org-latex-preview-live-display-type' now accepts the symbols
buffer and eldoc as values.  When it is set to eldoc and live
previews are enabled, display of the continuously updated previews is
handled by Eldoc.  Note that previewing larger images with Eldoc may
require `eldoc-echo-area-use-multiline-p' and `max-mini-window-height'
to be set appropriately.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur c14452c601
org-latex-preview: Add support for live previews
* lisp/org-latex-preview.el (org-latex-preview-auto-generate,
org-latex-preview-live-preview-inline, org-latex-preview-throttle,
org-latex-preview-debounce, org-latex-preview-live-display-type,
org-latex-preview-live--debounce,
org-latex-preview-live--throttle,
org-latex-preview-live--clearout,
org-latex-preview-live--regenerate,
org-latex-preview-live--update-props,
org-latex-preview-live--ensure-overlay,
org-latex-preview-live--update-overlay,
org-latex-preview-live--setup, org-latex-preview-live--teardown,
org-latex-preview-live--docstring,
org-latex-preview-live--element-type,
org-latex-preview-live--generator,
org-latex-preview--ensure-overlay,
org-latex-preview--failure-callback,
org-latex-preview--svg-make-fg-currentColor): Add support for
live-previewing LaTeX fragments.  When
`org-latex-preview-auto-generate' is set to the symbol live and
`org-latex-preview-auto-mode' is turned on, LaTeX previews are
continuously updated when editing a LaTeX fragment.  These
previews are shown to the right of or below the fragment.  The
preview generation timing can be controlled using the options
`org-latex-preview-debounce' and `org-latex-preview-throttle'.
2024-04-01 19:50:45 +08:00
TEC f19428e6ca
org-latex-preview: Update copyright years 2024-04-01 19:50:45 +08:00
TEC 950b45baf3
org-latex-preview: Put :page-width in opt plist
* lisp/org-latex-preview.el (org-latex-preview-options,
org-latex-preview-appearance-options): Rename
`org-latex-preview-options' to `org-latex-preview-appearance-options',
as it better reflects the purpose of the variable.

(org-latex-preview--tex-styled, org-latex-preview--image-extract-async,
org-latex-preview--create-tex-file,
org-latex-preview--create-image-async, org-latex-preview--hash,
org-latex-preview-place, org-latex-preview--update-overlay): Put the
page width specification in `org-latex-preview-appearance-options', and
adjust existing code to handle this new structuring.

* lisp/ox-html.el (org-html-prepare-latex-images,
org-html-latex-image-options): Adjust for the
`org-latex-preview-appearance-options' rename, and put :page-width in
the options plist, just with a raised value of 1.0 as the HTML default.

* lisp/org.el (org-do-latex-and-related, org-latex-preview-options),
org-compute-latex-and-related-regexp): Adjust for the
`org-latex-preview-appearance-options' rename.

* lisp/org-compat.el: Adjust for the
`org-latex-preview-appearance-options' rename.

* lisp/ob-latex.el (org-babel-execute:latex, org-latex-preview-header)):
Adjust for the `org-latex-preview-appearance-options' rename.

* etc/ORG-NEWS: Adjust for the `org-latex-preview-appearance-options'
rename.

* doc/org-manual.org (Previewing LaTeX fragments): Adjust for the
`org-latex-preview-appearance-options' rename.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 760a44d4d0
org-latex-preview: Fix preview help-echo property
* lisp/org-latex-preview.el (org-latex-preview--update-overlay):
Add LaTeX compilation errors to the help-echo property when the
cursor is inside the fragment that is being previewed.  This
primarily affects the use of `org-latex-preview-auto-mode`.
2024-04-01 19:50:45 +08:00
TEC 6d6a40550f
org-latex-preview: Improved face heuristics
* lisp/org-latex-preview.el (org-latex-preview--face-around): To work
around issues where syntax highlighting of the underlying LaTeX fragment
interferers with the foreground colour of the preview, we append default
to the face list regardless.

(org-latex-preview--ignored-faces): While we're improving face
heuristics, it's also come to my attention that whitespace-mode can
interferer with face selection, and whitespace-mode should also be
ignored.  Perhaps this should become part of the API?
2024-04-01 19:50:45 +08:00
TEC f67e8c044a
org-latex-preview: Support symbol entrypoint args
* lisp/org-latex-preview.el (org-latex-preview): Refactor to support a
symbol-value "mode" argument as well as prefix arguments.  This stops
forcing programmatic invocations from having to use uninformative
values, and actually makes the implementation slightly nicer to read I
think.

* lisp/org.el: Change the argument in the preview startup invocation to 'buffer.
2024-04-01 19:50:45 +08:00
TEC 4f1a971ab8
org-latex-preview: Robustify DPI calculation
* lisp/org-latex-preview.el (org-latex-preview--get-display-dpi): It was
reported that on a WSLg system using pgtk that
`org-latex-preview--get-display-dpi' produced an arithmetic overflow
error.  Inspecting the calculation performed and docstrings of functions
involved, it seems we need to be more careful of the `display-mm-height'
output.  We now guard against it being zero or nil, which should make
the DPI calculation more robust.

Simply falling back to a guessed DPI of 140 is non-ideal, but probably
the best we can reasonably do here.
2024-04-01 19:50:45 +08:00
TEC cf014a7e9f
org-latex-preview: Guard against deleted buf/ov
* lisp/org-latex-preview.el (org-latex-preview--place-images): Since the
image generation and placement is asynchronous, it is possible that in
the meantime the target overlay or even buffer could be deleted.  To
avoid errors, we simple check that this is not the case before
attempting to place preview images.
2024-04-01 19:50:45 +08:00
TEC c44bdba945
org-latex-preview: Still show errs with no tooltip
* lisp/org-latex-preview.el (org-latex-preview--update-overlay): When
`tooltip-mode' is not active, still show the error, just remove multiple
spaces to be economic with the horizontal room available.  This isn't
good as showing the tooltip, but it's better than not showing anything.
2024-04-01 19:50:45 +08:00
TEC 8a844272a3
org-macs: Set some process variables in org-async
* lisp/org-macs.el (org-async-call): When eking out maximum performance
from external commands, there are a few potentially important process
variables. `org-async-call' is extended to support setting these, with
default values that differ from Emacs' defaults but should enable better
performance in general.
2024-04-01 19:50:45 +08:00
TEC d2cb17132a
org-latex-preview: Mention latex buffer if no dvi
* lisp/org-latex-preview.el (org-latex-preview--failure-callback,
org-latex-preview--create-image-async): When the image conversion step
fails due to a missing input file, point the user to the LaTeX output
buffer instead of the image conversion output buffer.
2024-04-01 19:50:45 +08:00
TEC fead73f582
org-latex-preview: Include running command in bufs
* lisp/org-latex-preview.el (org-latex-preview--image-extract-async,
org-latex-preview--tex-compile-async): Add a comment at the start of the
process output buffers mentioning what the command being run is.
2024-04-01 19:50:45 +08:00
TEC a1e5c68730
org-latex-preview: Simplify color formatting
* lisp/org-latex-preview.el (org-latex-preview--format-color,
org-latex-preview--normalize-color): Use three decimal places, and
remove the now-obsolete `org-latex-preview--normalize-color'.

* lisp/org-compat.el (org-normalize-color): With the removal of the
`org-latex-preview--normalize-color' alias, mark `org-normalize-color'
as obsolete.
2024-04-01 19:50:45 +08:00
TEC 6b134f4556
org-latex-preview: Use dvisvgm 3.1+ currentcolor
* lisp/org-latex-preview.el (org-latex-preview--tex-styled,
org-latex-preview--svg-make-fg-currentColor,
org-latex-preview--dvisvgm-filter,
org-latex-preview--dvisvgm-version>=3.1): With dvisvgm 3.1+, it can
replace the foreground color with "currentColor" itself, and so we can
skip `org-latex-preview--svg-make-fg-currentColor' when we are using a
new enough dvisvgm.

(org-latex-preview--await-fragment-existance): Just in case the
asyncronicity in file writing causes issues, we keep the file existence
check (for now).
2024-04-01 19:50:45 +08:00
TEC 3a7635c475
org-latex-preview: Improve env numbering calc
* lisp/org-latex-preview.el (org-latex-preview--get-numbered-environments,
org-latex-preview--environment-numbering-table): Make numbering
calculations more accurate, at the expense of a ~10x increase in the
time to calculate numbering in a document, mitigated by the use of
caching — resulting in a ~2x improvement compared to the simpler method
in subsequent runs.

(org-latex-preview--numbered-environments,
org-latex-preview--numbered-environments-single,
org-latex-preview--numbered-environments-multi,
org-latex-preview--numbered-environments-all): Split
`org-latex-preview--numbered-environments' into
`org-latex-preview--numbered-environments-single' and
`org-latex-preview--numbered-environments-multi', then rename
`org-latex-preview--numbered-environments' to
`org-latex-preview--numbered-environments-all' for the sake of clarity.

Determining the count of numbered equations in a LaTeX environment is
non-trivial.  Previously, a simple heuristic was used that counted the
number of lines ending with "\\" in particular environments, then
subtracted the number of "\nonumber" and "\tag{...}" instances.

However, lines can end with "\\" without contributing to the number of
equations in the environment, consider the "cases" and "bmatrix"
environments.  To improve the heuristic, we (with some care) remove
/all/ inner environments from the LaTeX maths environment before
processing.  Since this takes more effort, we split the numbered
environments into those we know will contain exactly one numbered
equation where we can avoid the extra processing, and those that require
the more sophisticated heuristics.

The new org-element caching API is very helpful for recovering the
performance cost of this extra computation in the long run.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 48302eb332
org-latex-preview: Fix process filter timing errs
* lisp/org-latex-preview.el (org-latex-preview--create-image-async,
org-latex-preview--latex-preview-filter,
org-latex-preview--dvipng-filter, org-latex-preview--dvisvgm-filter,
org-latex-preview--place-images): The dvipng and latex-preview filters
run concurrently (interleaved), and both contribute image metadata.
So caching/placing images cannot be associated with the dvipng filter,
this leads to non-deterministic errors where preview images can have
incomplete metadata.  To fix this, check if we are using dvipng when
running the LaTeX filter, and place images from whichever of the two
filters processes each fragment second.

Refactor: Move the image placement/caching logic fully to
`org-latex-preview--place-images' instead of duplicating code in all
three (latex-filter, dvipng and dvisvgm) previews.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 6522e4b6ac
org-latex-preview: Fix LaTeX header on fails + reruns
*
lisp/org-latex-preview.el (org-latex-preview--check-all-fragments-produced):
When rerunning a preview run (because of catastrophic failures), pass
the LaTeX header used to the new process.  The current behavior passes
an empty header, which causes the process to fail again.
2024-04-01 19:50:45 +08:00
Karthik Chikmagalur 1cbb918439
org-latex-preview: Fix xelatex preview image sizes
*
lisp/org-latex-preview.el (org-latex-preview--include-preview-string,
org-latex-preview--latex-preview-filter):  when xetex is used,
preview.sty assumes PDF output by default and does not write any
postscript data to the output XDV file.  This makes dvisvgm unable to
correctly determine the preview geometry.  Fix by specifying the
`dvips' option to preview, which adds (apparently as a side effect)
this geometry information to the XDV file.

Remove a conditional in `org-latex-preview--latex-preview-filter' that
was previously used to attempt to work around this issue.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 281685ba84
ox-latex: Disable precompile for xelatex/lualatex
* lisp/ox-latex.el (org-latex-make-preamble): If xelatex or
lualatex are used for LaTeX export, disable LaTeX header
precompilation (via the CTAN package mylatexformat) locally in the
buffer and issue a warning.  Xelatex does not support
precompilation, and while Lualatex supports it in some cases, it
is best left unsupported by the Org LaTeX export process until
precompilation support for them improves upstream.

* lisp/org-latex-preview.el (org-latex-preview--create-tex-file):
Make the same changes as above when precompiling LaTeX headers
for LaTeX preview purposes.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 0e4463b941
org-latex-preview: Rename precompilation vars
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--latex-preview-filter,
org-latex-preview--create-tex-file,
org-latex-preview-use-precompilation, org-latex-preview--precompile):
Rename (i) the user option that controls precompilation for LaTeX
previews, and (ii) the function that precompiles headres for LaTeX
previews.  This makes the names shorter and consistent with their
corresponding equivalents in `ox-latex'.

Rename
`org-latex-preview-use-precompilation' -> `org-latex-preview-precompile'
`org-latex-preview-precompile' -> `org-latex-preview--precompile'

The new names have equivalents `org-latex-precompile' and
`org-latex--precompile' in `ox-latex'.

* testing/lisp/test-org-latex-preview.el: Update tests that set this
user option.

* etc/ORG-NEWS: Update the NEWS file.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur d89c3435e1
org-latex-preview: Fix bug clearing precompile cache
* lisp/org-latex-preview.el (org-latex-preview-clear-cache,
org-latex-preview--create-tex-file,
org-latex-preview--include-preview-string): LaTeX headers that are
precompiled include additional strings that set the
textwidth (according to `org-latex-preview-width') and include
preview.sty.  These strings are not appended to the header when
trying to clear the precompile cache for the present buffer.  Fix
by (i) removing the textwidth declaration from the precompiled
text, and (ii) including the preview.sty inclusion string with the
header we look for when trying to remove the corresponding fmt
file in the org-persist cache.

org-latex-preview--include-preview-string: Introduce string that
holds the text to include preview.sty in the document header.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 3979a20b7a
org-latex-preview: Reduce delay when re-rendering
*
lisp/org-latex-preview.el (org-latex-preview-auto--close-previous-overlay):
Reduce the delay when re-rendering fragments (with `org-latex-preview-auto-mode' turned
on) from 50 ms to 10 ms. This delay is a heuristic number for
perceived smoothness, and this change represents a tuning effort.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 7614d174ae
org-latex-preview: Change preview hashing parameters
* lisp/org-latex-preview.el (org-latex-preview--hash): Use only the
`:scale' parameter from `org-latex-preview-options' when hashing
fragments.  Other parameters like `:zoom' do not affect the content of
the image, so this helps avoid building up garbage in the org-persist
cache.  `org-latex-preview' is also faster since re-rendering images
is required less often.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 4eeba6a90e
org-latex-preview: Change hooks to abnormal hooks
*
lisp/org-latex-preview.el (org-latex-preview-auto--close-previous-overlay,
org-latex-preview-auto--open-this-overlay,
org-latex-preview-close-hook, org-latex-preview-open-hook): Change
`org-latex-preview-open-hook' and `org-latex-preview-close-hook' to
abnormal hooks that accept an overlay as the argument.  This makes it
easier to apply overlay-specific changes -- which is what these hooks
are primarily for -- without having to find the overlay by probing the
buffer first.

Rename:
`org-latex-preview-open-hook' to `org-latex-preview-open-functions'
`org-latex-preview-close-hook' to `org-latex-preview-close-functions'
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur bddc6c2d2e
org-latex-preview: Fix clear-cache command
* lisp/org-latex-preview.el (org-latex-preview-clear-cache): When
clearing the preview cache, clear the cached preamble after clearing
the image cache, since the preamble is used to compute the image
hashes.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 133d857209
test-org-latex-preview: Add preliminary tests
* testing/lisp/test-org-latex-preview.el: Tests for
org-latex-preview.el.

* testing/examples/org-latex-preview-test.org: Short but
full-featured document with LaTeX fragments to run tests on.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 8e64ee5c2c
org-latex-preview: Don't fully reset overlay state
* lisp/org-latex-preview.el (org-latex-preview--ensure-overlay,
org-latex-preview--update-overlay): When ensuring a preview overlay
exists, do not fully reset the state of the overlay, such as the
stored image spec, the flag that checks if the preview is open, etc.
Persisting prior state is required for the "live" preview
feature (introduced in the following commits) to function.  Similarly,
if "live" previewing a LaTeX element that has an overlay attached, do
not set the overlay face or error display indicator(s).
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 0c7d34d9ef
org-latex-preview: Add hooks for customization
* lisp/org-latex-preview.el (org-latex-preview-process-finish-functions,
org-latex-preview-update-overlay-hook, org-latex-preview-close-hook,
org-latex-preview-open-hook, org-latex-preview--create-image-async,
org-latex-preview-auto--handle-post-cursor,
org-latex-preview--run-finish-functions): Add four hooks for better
control of the LaTeX preview process.

`org-latex-preview-process-finish-functions': Runs after the image
conversion process. This is an abnormal hook: each hook function
accepts the same arguments as other `org-async' callbacks for this
process.

`org-latex-preview-close-hook' and `org-latex-preview-open-hook':
Run after a preview is closed (text hidden to reveal image) or
opened (image hidden to reveal text) respectively.

`org-latex-preview-update-overlay-functions': Run after a LaTeX
preview overlay is updated with a new image.  This is an abnormal
hook: each hook function accepts one argument, the overlay that was
updated.

The "live" preview system introduced in the following commits uses
these hooks, along with the facilities provided by
`org-latex-preview-auto-mode'.  In addition, these hooks will
prove useful when writing code that reuse the API afforded by
`org-latex-preview-place' to provide LaTeX previews for other
major modes.
2024-04-01 19:50:44 +08:00
TEC e134cbc9b6
org-latex-preview: Ignored cmds list for auto mode
* lisp/org-latex-preview.el (org-latex-preview-auto-blacklist): Add a
blacklist for commands that should not cause LaTeX preview overlays to
be "opened", i.e. for preview images to be hidden and text revealed when
using `org-latex-preview-auto-mode'.  A common use case would be cursor
navigation commands like `next-line' or `scroll-up-command' that are
often intended to move the view of the buffer, where opening preview
overlays can be distracting.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 882a2aa687
org-latex-preview: Fix overlay boundary deletion bug
*
lisp/org-latex-preview.el (org-latex-preview-auto--regenerate-overlay):
When `org-latex-preview-auto-mode' is active and a LaTeX fragment
or environment boundary is deleted,
`org-latex-preview-auto--regenerate-overlay' generates a new
preview for the new org-element at point, which is no longer a
LaTeX fragment or environment.  This results in paragraph text or
other syntax being captured into the preview.  Fix by adding a
check to ensure that the element post-change is still a LaTeX
fragment or environment.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 7497089eb5
org-latex-preview: non-buffer-local auto-marker bug
* lisp/org-latex-preview.el (org-latex-preview-auto--marker,
org-latex-preview-auto-mode): `org-latex-preview-auto--marker' is
initialized to a marker, which can cause it to not be
buffer-local.  Instead, initialize it to nil and explicitly set it
to a marker when running `org-latex-preview-auto-mode'.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur f8209c834c
org-latex-preview: Fix startup preamble generation
* lisp/org-latex-preview.el (org-latex-preview--get-preamble):
When `org-startup-with-latex-preview' (or the `#+startup:
latexpreview') option is set, preamble generation and
precompilation fail as latex previews are generated in the clone
of the current buffer created by `org-export-with-buffer-copy'.
This is because org-mode is turned on in the cloned buffer, which
requires creating LaTeX previews there.  Not only is this
unnecessary, it causes a flurry of errors since the cloned buffer
is killed before the previews can be placed.  Explicitly avoid
org-startup-* tasks in the cloned buffer when generating the LaTeX
preamble for our main Org buffer.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 34cdab7624
org-latex-preview: Ensure fmt file cache is cleared
* lisp/org-latex-preview.el (org-latex-preview-clear-cache): When
running `org-latex-preview-clear-cache', the precompiled format
file is only removed from the `org-persist' cache if the preamble
has been cached in the current buffer.  We require the format file
to always be unregistered from the cache, so generate the preamble
if necessary so it can be hashed and used as the key to find the
corresponding format file in the cache.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 2458b70617
org-latex-preview: Optimize overlay-modify hook
*
lisp/org-latex-preview.el (org-latex-preview-auto--mark-overlay-modified):
Reduce slightly the number of checks needed to run each time text
inside a LaTeX fragment overlay is modified.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 679a495139
Update ORG-NEWS
* etc/ORG-NEWS: Add summary of `org-latex-preview' changes.
2024-04-01 19:50:44 +08:00
Karthik Chikmagalur 5f40ac9fb7
org-manual: Update LaTeX preview section
* doc/org-manual.org (Previewing LaTeX fragments): Mention newly
added user options and `org-latex-preview-auto-mode'.
2024-04-01 19:50:44 +08:00
TEC 2af0f15c65
ox-html: Allow inlining of LaTeX images
* lisp/ox-html.el (org-html-latex-image, org-html-latex-image-options):
Add a new `org-html-latex-image-options' keyword, ":inline", which
controls image inlining in `org-html-latex-image'.
2024-04-01 19:50:44 +08:00
TEC 3b6dd1ab34
org-latex-preview: Emit warning when hyperref seen
* lisp/org-latex-preview.el (org-latex-preview--latex-preview-filter):
If during LaTeX compilation hyperref seems to be present, emit a warning
mentioning the sizing issue it is known to cause.
2024-04-01 19:50:44 +08:00
TEC b130fb3d9d
org-latex-preview: Add preview-order eqn numbering
* lisp/org-latex-preview.el (org-latex-preview--tex-styled,
org-latex-preview-numbered): Allow for preview-order based equation
numbering, by setting `org-latex-preview-numbered' to the symbol
"preview".
2024-04-01 19:50:44 +08:00
TEC ccf9d0cbf8
org-latex-preview: Use icon for non-numbered eqns
* lisp/org-latex-preview.el (org-latex-preview--get-preamble,
org-latex-preview--single-eqn-format): When numbering is turned off (via
`org-latex-preview-numbered'), instead of always showing "(1)" as the
equation number, use a diamond symbol, and in multiline environments
show +offset.  The LaTeX setup for this is stored in the new const
`org-latex-preview--single-eqn-format'.
2024-04-01 19:50:44 +08:00
TEC 59d820908e
org-latex-preview: Fix snippet preamble hash
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file,
org-latex-preview--hash, org-latex-preview-place,
org-latex-preview-clear-cache): The only the default preamble was being
hashed, which led to incorrect results across documents.  To correctly
hash the preamble, it is now determined at the start of
`org-latex-preview-place', and used in `org-latex-preview--hash',
`org-latex-preview--create-tex-file', and
`org-latex-preview-clear-cache'.
2024-04-01 19:50:44 +08:00
TEC a9ee570733
org-latex-preview: Set overlay priority to -80
* lisp/org-latex-preview.el (org-latex-preview--ensure-overlay): Setting
the overlay priority to -80 ensures that the background colour of
hl-line-mode's overlays takes priority, improving the visual consistency
of previews in the buffer.
2024-04-01 19:50:44 +08:00
TEC b8fcc3c5c8
ox-html: Update LaTeX export for images and mathml
* lisp/ox-html.el (org-html-latex-environment, org-html-format-latex,
org-latex-to-html-convert-command, org-format-latex-as-html,
org-html-latex-image-options): Introduce new functions and variables to
work directly with the new org-latex-preview and ox-mathml API.

* lisp/org-latex-preview.el (org-format-latex-as-html,
org-latex-preview--tex-styled, org-latex-preview-replace-fragments,
org-latex-to-html-convert-command, org-latex-preview-options,
org-latex-preview-place-image-link): Move all of the HTML-specific
processing out of org-latex-preview.el, and into ox-html.el, and remove
now-obsolete code.

* lisp/org-compat.el (org-place-formula-image, org-html-format-latex):
Relocate a copy of `org-place-formula-image' and `org-html-format-latex'
here, and mark them as obsolete.
2024-04-01 19:50:44 +08:00
TEC 4011531ff6
ox-mathml: Refactor mathml export
* lisp/ox-mathml.el: Introduce a new library for managing mathml conversion.

* lisp/org-latex-preview.el (org-create-math-formula,
org-format-latex-mathml-available-p, org-latex-to-mathml-jar-file): Move
the various mathml functions into ox-mathml.

* lisp/org-compat.el: Add compat entries for the various mathml
conversion functions that have now been brought under ox-mathml.

* lisp/ox-odt.el (org-odt-export-as-odf,
org-odt--translate-latex-fragments): Use the new org-mathml functions.
2024-04-01 19:50:43 +08:00
TEC 7ee7a422a9
org: Update LaTeX overlay during fontification
* lisp/org.el (org-do-latex-and-related, org-latex-preview-options): To
ensure that LaTeX preview overlays update as the face changes (for
instance, when in a heading that changes level), the face used is
updated during fontification when applicable.  This also ensures that
the correct face is used when JIT fontification is active.
2024-04-01 19:43:19 +08:00
TEC f729137369
org-latex-preview: Improved face adaptation
* lisp/org-latex-preview.el (org-latex-preview--face-around): Instead of
only examining the face immediately before the LaTeX snippet, also look
at the face immediately after before determining the appropriate face to
use.  This is relevant when the prior face is
uninformative (e.g. org-indent) but the latter face contains the
applicable face (e.g. org-list-dt).  Determination of the applicable
face is now performed in the new function
`org-latex-preview--face-around'.
(org-latex-preview--colors-at, org-latex-preview--update-overlay):
Rename `org-latex-preview--colors-at' to
`org-latex-preview--colors-around', and use
`org-latex-preview--face-around' for better face determination.
(org-latex-preview-place, org-latex-preview-clear-cache): Update to
provide an "end" value to `org-latex-preview--colors-around'.
2024-04-01 19:43:19 +08:00
TEC e044b11178
org-latex-preview: Better handle temp/remote files
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--create-tex-file): Before obtaining the (compiled)
preamble, check for the temp-ness and remote-ness of the file, and act
accordingly.  Non-temp remote files are not currently supported, and an
error will now be thrown in such cases.  The temporary file status is
now passed on to `org-latex-preview-precompile' and through to
`org-latex--precompile'.
2024-04-01 19:43:19 +08:00
TEC f3cddf12b9
ox-latex: Handle preamble temp-ness explicitly
* lisp/ox-latex.el (org-latex--precompile, org-latex-make-preamble):
Instead of detecting relative file includes within
`org-latex--precompile', have an optional argument to signal a file can
be safely compile in the tempdir.  Move the check to
`org-latex-make-preamble' when calling `org-latex--precompile'.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur b43f84284d
org-latex-preview: Clean up tex file on failure
*
lisp/org-latex-preview.el (org-latex-preview--create-image-async):
Ensure that the latex-preview cleanup callback runs when the
preview image extraction process fails.  This is to avoid
littering the default-directory with temporary tex files.
2024-04-01 19:43:19 +08:00
TEC 345fd6a137
org-latex-preview: Work around XeTeX misbehaviour
* lisp/org-latex-preview.el (org-latex-preview--latex-preview-filter):
Since XeLaTeX seems to misbehave with tightpage, we special-case the
tightpage processing to account for it.
2024-04-01 19:43:19 +08:00
TEC 1c72961d71
org-latex-preview: Improved error messages
* lisp/org-latex-preview.el (org-latex-preview--image-extract-async,
org-latex-preview--tex-compile-async,
org-latex-preview--create-image-async): Edit the error messages for
LaTeX compilation and image generation failure to be slightly more informative.
2024-04-01 19:43:19 +08:00
TEC 6c08992317
org-latex-preview: Disable buf precompile on error
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file): When
an error occurs during LaTeX precompilation, disable it using
`setq-local' and emit an informative warning message.
2024-04-01 19:43:19 +08:00
TEC bc9d9fa46f
org-latex-preview: Use stand-in color for SVG fg
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor,
org-latex-preview-place): Instead of guessing the SVG foreground to be
the first color seen, set a static stand-in color that is unlikely to
occur organically.
2024-04-01 19:43:19 +08:00
TEC cfd97b2183
org-latex-preview: Guard against caching nil-files
* lisp/org-latex-preview.el (org-latex-preview--cache-image): When
caching an image with `org-latex-preview--cache-image', check that the
image path is non-nil.  Should this not be true, a warning message is
emitted suggesting this is a bug that should be reported to the Org
mailing list.
2024-04-01 19:43:19 +08:00
TEC f1ba3addfc
org-latex-preview: Get a list of all started tasks
* lisp/org-latex-preview.el (org-latex-preview--create-image-async):
Instead of just returning the main tex-compile task, return a list of
all async tasks created (i.e. the dvipng task, when used).  This will
allow for `org-async-wait-for' to be used on the list to wait until all
processing has completed.
2024-04-01 19:43:19 +08:00
TEC a02e2c4116
org-latex-preview: Split out entry construction
* lisp/org-latex-preview.el (org-latex-preview--place-from-elements,
org-latex-preview--construct-entries): Split the entry construction code
into its own function `org-latex-preview--construct-entries'.

This change will make it easier to generate previews during export.
2024-04-01 19:43:19 +08:00
TEC eb426ec723
org-latex-preview: Construct numbering from tree
* lisp/org-latex-preview.el (org-latex-preview--get-numbered-environments,
org-latex-preview--environment-numbering-table): Extend
`org-latex-preview--get-numbered-environments' and
`org-latex-preview--environment-numbering-table' to accept a parse tree
to operate on as an optional argument.

This will be useful when trying to integrate numbering with exports.
2024-04-01 19:43:19 +08:00
TEC c1bf296d61
org-latex-preview: Wait for SVGs more robustly
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor,
org-latex-preview--dvisvgm-filter): Instead of waiting 0.01s and hoping
that an SVG exists by that point, we can wait and check for the
existance of an SVG within
`org-latex-preview--svg-make-fg-currentColor', and that should reduce
the chance of edge cases where the delay is insufficient.
(org-latex-preview--svg-make-fg-currentColor): Adjust the
`buffer-substring' call to not error when the buffer is empty.
2024-04-01 19:43:19 +08:00
TEC cfe5c2b3a4
org-latex-preview: Move org-format-latex to compat
* lisp/org-latex-preview.el (org-latex-preview-create-image,
org-format-latex): It has become apparent that it is not reasonably
possible to maintain the behaviour of `org-format-latex' and
`org-create-formula-image' using the new image, so instead put the
original implementations in org-compat.
(org-preview-latex-image-directory): Move and mark as obsolete in
org-compat as it has not be used.

* lisp/org-compat.el: Introduce the original `org-format-latex' and
`org-create-formula-image' definitions.  Also move
`org-preview-latex-image-directory' here and mark as obsolete, since it
has ended up being completely unused.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 46fb7e0959
org-latex-preview: Get geometry from preview.sty
* lisp/org-latex-preview.el (org-latex-preview--latex-preview-filter,
org-latex-preview--tex-scale-divisor,
org-latex-preview--dvipng-dpi-pt-factor): Fetch image geometry and
alignment information from the LaTeX compilation output instead of
dvisvgm or dvipng.  This calculation is simpler and should work for all
image converters (including imagemagick) and with all latex
processors (including xelatex and lualatex).

(org-latex-preview--shameful-magic-tex-scaling-factor): New
variable to match image geometry reported by preview.sty and that
computed by dvisvgm.

(org-latex-preview--dvipng-filter, org-latex-preview--dvisvgm-filter,
org-latex-preview--latex-preview-filter,
org-latex-preview--display-info): Adjust to no longer use the old sizing
information.

* lisp/org-latex-preview.el (org-latex-preview-process-alist,
org-latex-preview-create-image, org-latex-preview--display-info,
org-latex-preview--image-extract-async): Remove the :image-size-adjust
keyword, as with the new geometry detection system it is redundant.

We tried also switching dvisgm from "--bbox=preview" to "--exact-bbox",
as it should no longer be needed, but testing found "--exact-bbox" to
cause sizing issues in practice.
2024-04-01 19:43:19 +08:00
TEC 0661150b94
org-latex-preview: Introduce a place-preview arg
* lisp/org-latex-preview.el (org-latex-preview--dvipng-filter,
org-latex-preview--dvisvgm-filter,
org-latex-preview--check-all-fragments-produced,
org-latex-preview--generic-callback,
org-latex-preview--create-image-async, org-latex-preview-place):
Refactor the preview pipeline to use a "place-preview" argument to
indicate that LaTeX previews should be placed after generation.

This change will pave the way for use with export, where the LaTeX
preview should be generated but not previewed.
2024-04-01 19:43:19 +08:00
TEC 3f4e5cfbb6
ox-latex: Precompile preamble for export
* lisp/ox-latex.el (org-latex-precompile, org-latex-make-preamble): Make
use of "mylatexformat" to precompile the LaTeX preamble, for faster
exports.
(org-latex--remove-cached-preamble): Add a function to clear a cached
preamble.

* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--get-preamble): Relocate the precompilation
functionality to ox-latex.el, and use the new ox-latex preamble
precompilation API.
(org-latex-preview-clear-cache): Use the new preamble cache clearing
functionality in ox-latex.
2024-04-01 19:43:19 +08:00
TEC 02a9d3b3c4
org-latex-preview: Use org-persist for .fmt cache
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--create-tex-file): Cache compiled ".fmt" format dump
files with org-persist, instead of using predictably named tempfiles.
`org-latex-preview--precompile-preamble' is introduced to seperate out
the compilation process from the org-persist interaction.  As a result
of the new changes, the ".fmt" extension is also returned now, and so it
must be stripped in `org-latex-preview--create-tex-file'.
2024-04-01 19:43:19 +08:00
TEC adda26940c
org-latex-preview: Rework auto toggle behaviour
* lisp/org-latex-preview.el (org-latex-preview--auto-aware-toggle):
Adjust the toggle behaviour to hopefully behave more intuitively.
2024-04-01 19:43:19 +08:00
TEC 54664d5db0
org-latex-preview: org-latex-conditional-features
* lisp/org-latex-preview.el (org-latex-preview--get-preamble):
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 0ff0301b23
org-latex-preview: Reduce verbosity of messaging
* lisp/org-latex-preview.el (org-latex-preview--cleanup-callback,
org-latex-preview--create-image-async, org-latex-preview-place,
org-latex-preview--auto-aware-toggle, org-latex-preview,
org-latex-preview-auto--regenerate-overlay): Do not emit a message
when previewing is successful.  This reduces how "busy" the echo area
is, especially when `org-latex-preview-auto-mode' is on.  When
previewing fails, display a message as before (behaviour unchanged).
2024-04-01 19:43:19 +08:00
TEC b5497272b0
org-latex-preview: Lazy-load, with autoloads
* lisp/org.el: No longer require org-latex-preview.

* lisp/org-latex-preview.el: Require the relevant files, and add
autoload tokens to `org-latex-preview-options',
`org-latex-preview-process-alist' (for backwards compatibility),
`org-latex-preview-auto-mode', `org-latex-preview' (the major likely
entry points), and `org-latex-preview-place` (potential external entry
point).
2024-04-01 19:43:19 +08:00
TEC d3f92370f1
org-latex-preview: Use the conditional preamble
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file,
org-latex-preview--clear-preamble-cache): Instead using a minimal info
export plist, populate it with buffer-specific values so that the
conditional preamble can be appropriately generated, and cache the
result.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur e65deb29c1
org-latex-preview: Speed up texfile creation time
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file):
Speed up texfile creation time by inhibiting fsync and setting the
`coding-system-for-write' explicitly.  Times are reduced by about
40-50%.
2024-04-01 19:43:19 +08:00
TEC 9f96a9030d
org-latex-preview: Fix spacing before LaTeX envs
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file): Set
the \abovedisplayskip length to zero to remove the default padding.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 4234d8bca1
org-latex-preview: Fix element start positions
* lisp/org-latex-preview.el (org-latex-preview--place-from-elements,
org-latex-preview-auto--maybe-track-element-here): The org-element
property `:begin' includes any Org keyword text associated with the
element, such as "#+RESULTS:" or "#+ATTR_LATEX:" and these are swallowed
up in the created preview overlays.  Fix by using the `:post-affiliated'
property over `:begin' when it is available.  Note that some
calculations, such as equation numbering, still use the `:begin'
keyword.  These calculations don't involve creating overlays and thus
this is not (expected to be) an issue.
2024-04-01 19:43:19 +08:00
TEC 0ace117f3a
org-macs: Support blocking on async tasks
* lisp/org-macs.el (org-async--blocking-tasks, org-async-wait-for,
org-async--cleanup-process, org-async--execute-callback): Add support
for waiting for a set of async tasks to complete via the new function
`org-async-wait-for'.
2024-04-01 19:43:19 +08:00
TEC 3d267c442c
org-latex-preview: Redesign preview creation API
* lisp/org-latex-preview.el (org-latex-preview--check-all-fragments-produced,
org-latex-preview--create, org-latex-preview-fragments,
org-latex-preview-auto--regenerate-overlay,
org-latex-preview-auto--detect-fragments-in-change): Split the
org-element processing and the preview creation components of
`org-latex-preview--create` into two new functions, `
org-latex-preview--place-from-elements' and `org-latex-preview-place'.
The latter of these can serve as a convenient public API for creating
fragments.
(org-latex-preview-place, org-latex-preview-create-image-async): To make
`org-latex-preview-place' this easier to use, we also allow the LaTeX
preamble to be provided as an optional argument, and adjust
`org-latex-preview-create-image-async' to add this as the :latex-header
to the processing-info plist.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur cad593edd0
org-latex-preview: Better imagemagick cleanup
* lisp/org-latex-preview.el (org-latex-preview--generic-callback,
org-latex-preview-create-image-async,
org-latex-preview-process-alist): Reuse
`org-latex-preview--cleanup-callback' for imagemagick-based previews.
Additionally, check produced fragments and regenerate them if
necessary.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur d859b033b2
org-latex-preview: Fix auto-gen at end of overlay
* lisp/org-latex-preview.el (org-latex-preview-auto--maybe-track-element-here):
`overlays-at' does not include overlays that end at the position it is
called on.  This caused auto-generation to not trigger immediately
when manually typing the closing delimiters of a LaTeX fragment. Fix
this by recording the position just before the end of a newly created overlay.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 144eea637a
org-latex-preview: Respect auto-generate option
* lisp/org-latex-preview.el (org-latex-preview-auto--detect-fragments-in-change):
Respect the user option `org-latex-preview-auto-generate' when
`org-latex-preview-auto-mode' is active.  (This was lost when the
auto-generation code was rewritten.)
2024-04-01 19:43:19 +08:00
TEC 50a526dbca
org-latex-preview: Use appropriate TeX compiler
* lisp/org-latex-preview.el (org-latex-preview--tex-compile-async,
org-latex-preview-process-alist): Introduce %l and %L placeholders for
the LaTeX compiler.
(org-latex-preview-precompile): Record the LaTeX compiler in the
preamble hash, and add %l/%L to the `org-compile-file' format spec.
(org-latex-preview-compiler-command-map): Introduce a new variable to
map each LaTeX compiler name to the command and arguments needed.

Note that due to idiosyncrasies in how the various TeX compilers behave,
pdfLaTeX will likely continue to provide a smoother experience.  In the
future, some work can be done to improve this situation.
2024-04-01 19:43:19 +08:00
TEC a75a426620
org-latex-preview: Allow setting persist expiry
* lisp/org-latex-preview.el (org-latex-preview--cache-image,
org-latex-preview-persist-expiry): Introduce a new variable
`org-latex-preview-persist-expiry' which is used within
`org-latex-preview--cache-image' as the expiry value when calling
`org-persist-register' on preview data.
2024-04-01 19:43:19 +08:00
TEC 7f424afbad
org-latex-preview: Customisable preview width
* lisp/org-latex-preview.el (org-latex-preview--create-tex-file,
org-latex-preview-width ): Introduce a new variable
`org-latex-preview-width' for convenient setting of the preview width,
and use it in the preamble generation.
(org-latex-preview-header): Remove now-redundant content (thanks to the
use of preview.sty).
2024-04-01 19:43:19 +08:00
TEC ae7d914606
org-latex-preview: Wait for complete SVG file
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor):
Wait until the SVG file is complete before processing it.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 649bf05560
org-latex-preview: Custom processing indicator
* lisp/org-latex-preview.el (org-latex-preview-create-image-async,
org-latex-preview--update-overlay, org-latex-preview--ensure-overlay):
These functions are modified to incorporate customizable visual
indication of preview processing.
(org-latex-preview-processing-indicator): User option to customize how
preview processing is indicated visually.  The current options are:
no indication, show a fringe marker, or apply the
face `org-latex-preview-processing-face'.  The fringe marker is
currently set as the default.
(org-latex-preview--indicate-processing): Add function to handle
applying the appropriate processing indicator.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 69a1aca864
org-latex-preview: Compile previews in default-dir
* lisp/org-latex-preview.el (org-latex-preview--generic-callback,
org-latex-preview--tex-compile-async,
org-latex-preview--create-tex-file): Compile latex fragments in
`default-directory', with output placed in `temporary-file-directory'.
This is to ensure that relative paths in fragments (such as paths to
figures) are parsed correctly.  Note that relative paths in the header
are handled during precompilation instead.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 9b0b49f731
org-latex-preview: Rename filename parts uniformly
* lisp/org-latex-preview.el (org-latex-preview-create-image,
org-latex-preview--dvipng-filter, org-latex-preview--generic-callback,
org-latex-preview--do-cleanup,
org-latex-preview--image-extract-async): Adopt the following
convention for parts of file names used in the latex and image
processing: For file with path 'foo', foo-base refers to its base
name (no directory, no extension) and foo-no-ext refers to its full
path but without a file extension.  The third option (no directory
component but with file extension) is not used in org-latex-preview.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur d9d70aa861
org-latex-preview: Precompile with relative paths
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview-process-alist): Change the precompilation parameters
so the created format file includes all files included/input in the
header with paths relative to the original Org buffer.  The
precompilation is carried out by calling latex from the
`default-directory', with the source tex file and destination format
dump file both placed in `temporary-file-directory'.  Additionally the
source tex file for precompilation is deleted if the precompilation is
successful.
2024-04-01 19:43:19 +08:00
TEC c782d72cdc
org-persist: Add situational write inhibition
* lisp/org-persist.el (org-persist-write, org-persist--inhibit-write): TODO
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur c394fee2af
org-latex-preview: Compile latex in default-dir
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--do-cleanup, org-latex-preview--image-extract-async,
org-latex-preview--tex-compile-async,
org-latex-preview--create-tex-file): Format dump-files can be referred
to by their full paths in latex file preambles by adding a space after the "%&"
token.  Using this, we can compile the tex file containing the
previews in the same directory as the org file and handle relative
file references.  The above functions now do the following:
- format dump-file: Compiled and placed in
temporary-file-directory (no change)
- preview tex file: Refers to the format dump file in
temporary-file-directory. Compiled in default-directory, with output to
default-directory.
- image processors: Input (from tex output) in and output to
temporary-file-directory.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur a58c5ca459
org-latex-preview: Indicate errors when using pngs
* lisp/org-latex-preview.el (org-latex-preview--update-overlay,
org-latex-preview--ensure-overlay): When using dvipng, latex errors
cannot be indicated using an error face, and if a preview is generated
it is indistinguishable from a correct one.  Fall back to a fringe
marker in this situation.
2024-04-01 19:43:19 +08:00
TEC d6de767b78
org-latex-preview: Introduce auto-aware toggling
* lisp/org-latex-preview.el (org-latex-preview--auto-aware-toggle,
org-latex-preview): Toggling of fragments with auto-mode active needs a
bit of work to function as most people would likely expect.  To provide
this more nuanced behaviour a new function
`org-latex-preview--auto-aware-toggle' is created and replaces the prior
"toggle this element" implementation in `org-latex-preview'.
2024-04-01 19:43:19 +08:00
TEC 3048837260
org-latex-preview: Document async image logic
* lisp/org-latex-preview.el (org-latex-preview-create-image-async):
Explain the async call structure/logic with a large code comment.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur a2f3ca0409
org-latex-preview: Add error reporting via tooltip
* lisp/org-latex-preview.el (org-latex-preview--update-overlay): Add a
rudimentary interface for viewing compile errors (via tooltip).
2024-04-01 19:43:19 +08:00
TEC 9dafa0391b
org-persist: Fallback to associated files in write
* lisp/org-persist.el (org-persist-write:file): If the path given in a
file container does not exist, instead of returning nothing return the
associated path if possible.  This fixes an issue where should the
original file be deleted and `org-persist-write-all' be run, then the
file container's association will be set to nil and so when
`org-persist-gc' is run the nil path will cause
org-persist-associated-files:file to produce an error.
2024-04-01 19:43:19 +08:00
TEC 2b9d4097ef
org-latex-preview: Fix face checking
* lisp/org-latex-preview.el (org-latex-preview--resolved-faces-attr,
org-latex-preview--update-overlay): Handle more of the complexity of the
forms of face specifications, and avoid inheriting information from the
`org-indent' face, which is never useful.
2024-04-01 19:43:19 +08:00
TEC eb1afd8fe5
org-latex-preview: Wait for dvisvgm to write
* lisp/org-latex-preview.el (org-latex-preview--dvisvgm-filter): As
mentioned in the code comment, dvisvgm seems to sometimes lie about when
file content has been written, so we need to work around that by waiting
a little bit.
(org-latex-preview--cleanup-callback): Now that the svg processing is on
a timer, we must be careful not to run the callback to soon.  This isn't
desperately urgent, so we can use a relatively generous timer for this.
2024-04-01 19:43:19 +08:00
TEC cb8eda11ef
org-latex-preview: Adjust defaults
* lisp/org-latex-preview.el (org-latex-preview,
org-latex-to-html-convert-command, org-latex-preview-process-alist):
Adjust the default LaTeX preview parameters to better suit the reworked
preview system.
2024-04-01 19:43:19 +08:00
TEC 84e04d3840
org-latex-preview: Equation numbering
* lisp/org-latex-preview.el (org-latex-preview-numbered): Introduce a
new variable to signal whether equations numbering should be calculated
to be correct throughout the document, or not.
(org-latex-preview--numbered-environments): Create a list of known
numbered environments.
(org-latex-preview--environment-numbering-table,
org-latex-preview--get-numbered-environments): Introduce functions which
create a numbering hash table from the buffer.
(org-latex-preview--tex-styled): When an initial equation number is
provided, add LaTeX code to set the counter to apply the numbering.
(org-latex-preview--create,
org-latex-preview-auto--detect-fragments-in-change,
org-latex-preview--create): Make use of the new equation numbering
facilities.
(org-latex-preview--hash): Include first equation number (if applicable)
in the hash.
(org-latex-preview-clear-cache): Use numbering information.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur cfa2d97ee1
org-latex-preview: Simplify overlay regeneration
* lisp/org-latex-preview.el (org-latex-preview--close-previous-overlay,
org-latex-preview--regenerate-overlay): Overlays carry information
about the buffer they belong to, so it is unnecessary to pass this
information explicitly when passing an overlay argument to a function.
2024-04-01 19:43:19 +08:00
TEC c127685066
org-latex-preview: Reuse overlays more
* lisp/org-latex-preview.el (org-latex-preview--create,
org-latex-preview--maybe-track-element-here,
org-latex-preview--make-overlay): Instead of always deleting and
re-creating overlays in a region when wanting to ensure a suitable
overlay exists, we can look at the scanned overlays, check if a suitable
overlay already exists, and re-use it.  To indicate the change in
behaviour, as well as documentation updates
`org-latex-preview--make-overlay' is renamed to
`org-latex-preview--ensure-overlay'.  While we're at it, the
"front-advance" argument is now set when calling `make-overlay', to make
sure that text typed at the beginning of the fragment is not absorbed
into the overlay.
(org-latex-preview--failure-callback): It's possible the overlay
provided could be nil when something goes wrong, in which case do
nothing.
(org-latex-preview--mark-overlay-modified): Move to a separate function
for neatness.
2024-04-01 19:43:19 +08:00
TEC 3af9fbe676
org-latex-preview: Better fragment insertion check
* lisp/org-latex-preview.el (org-latex-preview--handle-insert,
org-latex-preview--detect-fragments-in-change, ): Replace the old
checker `org-latex-preview--handle-insert' that was called as a
`post-insert-hook' with a new method of checking for newly created
fragments based on buffer modifications as a `after-change-functions'
hook.  This has a number of benefits, including generally improved
robustness, and the removal of a reliance on font-lock information.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 37892b2394
org-latex-preview: Previews stored in /tmp
* lisp/org-latex-preview.el (org-latex-preview--get-cached,
org-latex-preview--remove-cached, org-latex-preview--cache-image):
These functions are modified to search in, remove from or add to a
session cache instead of org-persist's cache.
(org-latex-preview-persist-p): User option to turn off or on
persistent caching.
(org-latex-preview--table): Hash table used to hold preview image
metadata when using a session cache instead of org-persist.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur c385dbef3b
org-latex-preview: Fix precomp when backend switch
* lisp/org-latex-preview: (org-latex-preview-process-alist,
org-latex-preview-precompile): Update programs required for
imagemagick conversion to include pdflatex.  Precompilation now
generates a new format file when switching
`org-latex-preview-default-process' to or from imagemagick.
2024-04-01 19:43:19 +08:00
TEC 79fd6c73d3
org-macs: Ensure that filter run before callbacks
* lisp/org-macs.el (org-async--cleanup-process): Run
`accept-process-output` until no further output is fetched on process
exit, so we can assume that the callbacks are run after all filter
invocations.
2024-04-01 19:43:19 +08:00
TEC 29b5c7a313
org-macs: Add :coding kwarg to org-async-call
* lisp/org-macs.el (org-async-call): It is recommended in
(info "(elisp) Decoding Output") that the process coding system be set.
To allow for this we add a new keyword argument, :coding, and set the
default value to utf-8.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur cef68937dc
org-latex-preview: Improve preview creation msg
* lisp/org-latex-preview.el: (org-latex-preview,
org-latex-preview-create-image-async): `org-latex-preview' starts an
async process, and so it can only inform the user of the start of the
process. Information about the completion (to success or failure) is
provided by the relevant process sentinels instead.
(org-latex-preview--latex-log, org-latex-preview--image-log,
org-latex-preview--precompile-log): Log buffer names for preview latex
processing.
(org-latex-preview--tex-compile-async,
org-latex-preview--image-extract-async, org-latex-preview-precompile,
org-latex-preview-create-image): Use the newly created log buffer name
variables.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 1dabf70791
org-latex-preview: Clear failed preview overlays
* lisp/org-latex-preview.el: (org-latex-preview-create-image-async): If
preview images fail to generate for some or all LaTeX fragments, the
overlays placed on the fragments during processing need to be cleared.
This is done by adding a (failure) callback function to the image
generation process.
(org-latex-preview--failure-callback): Add callback that clears overlays
for previews that fail to generate.  Other behaviours are possible here
but not implemented yet.  This includes signalling failure by changing
how the overlays are displayed, such as by adding a face or fringe
marker.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur b1e096973c
org-latex-preview: Make clear-cache user-friendly
* lisp/org-latex-preview.el (org-latex-preview-clear-cache): Ask for
confirmation before wiping the entire LaTeX preview cache, and confirm
cache clearing at the end when clearing the buffer cache.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 794a40975b
org-latex-preview: Add cache clearing function
* lisp/org-latex-preview.el (org-latex-preview-clear-cache): Clears the
latex preview cache for LaTeX fragments in a region.  This can be called
as a command by itself, but is primarily required when previewing
fragments by force-regenerating their preview images.  This might be
necessary when the output image corresponding to a fragment is malformed
in some way, for instance.
2024-04-01 19:43:19 +08:00
TEC e6bf7188d7
org-latex-preview: More robust face resolving
* lisp/org-latex-preview.el (org-latex-preview--colors-at,
org-latex-preview--resolved-faces-attr): Just using `face-attribute' on
the first face spec given when the face text property is a list is too
naive.  To do this correctly, a new function
`org-latex-preview--resolved-faces-attr' is introduced which takes care
of the annoying semantics, and used in `org-latex-preview--colors-at' to
better resolve the face attribute.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur e5747394e0
org-latex-preview: Split org-latex-preview--create
* lisp/org-latex-preview.el (org-latex-preview--create): This function
does many tasks, including computing face colors and hashes for
fragments.  Split this function into three to reuse the parts for other
planned purposes, such as clearing cached images.
(org-latex-preview--colors-at): Finds appropriate foreground and
background colors at a position for the preview image of a LaTeX
fragment.  Also improve the code to handle multiple faces.
(org-latex-preview--hash): Computes the hash key for a LaTeX fragment
combined with relevant processing metadata.  This key is used to
identify the fragment when caching and placing images.
2024-04-01 19:43:19 +08:00
TEC 91ef8609bb
org-latex-preview: Graceful precompile failure
* lisp/org-latex-preview.el (org-latex-preview-precompile,
org-latex-preview--create-tex-file): Fall back to compiling without
using a preamble format file if the preamble could not be precompiled
without error.  In such an event, alert the user that preamble
precompilation failed, and in particular let them know if mylatexformat
could not be found.
2024-04-01 19:43:19 +08:00
TEC 3dc443d6a6
org-latex-preview: Check all fragments produced
* lisp/org-latex-preview.el (org-latex-preview--check-all-fragments-produced):
Create a new callback that checks that each fragment has indeed been
produced not, and if not guesses the last produced fragment caused a
problem.  The last produced fragment is then marked as erroneous,
its cache entry updated (replaced and re-inserted), and the remaining
fragments are regenerated.
(org-latex-preview-create-image-async): Run
`org-latex-preview--check-all-fragments-produced' after successfully
extracting images.
(org-latex-preview--cache-name, org-latex-preview--cache-image,
org-latex-preview--get-cached): Use a defconst instead of hardcoding the
cache container string in `org-latex-preview--cache-image' and
`org-latex-preview--get-cached'.
(org-latex-preview--remove-cached): Easy removal of an item from the
org-persist cache, as a counterpart to `org-latex-preview--cache-image'.
2024-04-01 19:43:19 +08:00
TEC ebfc7deaef
org-latex-preview: Strip redundant color switching
* lisp/org-latex-preview.el (org-latex-preview--create,
org-latex-preview--create-tex-file): Keep track of the last fragment's
foreground/background color, and only include LaTeX color specifications
as needed.
(org-latex-preview-create-image-async): Provide the processing type so
`org-latex-preview--create-tex-file' can change the style of color
setting as appropriate.  This allows the dvipng route to use postscript
special statements instead of regular color declarations.
2024-04-01 19:43:19 +08:00
TEC 12caf773c9
org-latex-preview: Do not show empty SVG fragments
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor):
When an SVG is empty, delete it.  This will cause
`org-latex-preview--cache-image' to give nil as the path.  When the
provided path is nil, do nothing.
(org-latex-preview--update-overlay): If the image path is nil, do
attempt to place an image.  If an error is recorded and there is no
image this causes the text to be shown with the error face.
(org-latex-preview--cleanup-callback): If the image path is nil, do not
try to delete it.
2024-04-01 19:43:19 +08:00
TEC c0c1481bbb
org-persist: Allow inhibiting of normalisation
* lisp/org-persist.el (org-persist-register,
org-persist--normalize-container,
org-persist--inhibit-container-normalization): Since container
normalisation is applied frequently (via
`org-persist--normalize-container'), when registering many new
containers the cost can quickly add up.  To avoid redundant overhead,
after normalising the container initially in `org-persist-register' we
bind a new variable `org-persist--inhibit-container-normalization' to t
and adjust `org-persist--normalize-container' to do nothing when this
new variable is non-nil.
2024-04-01 19:43:19 +08:00
TEC a4ae055d17
org-latex-preview: Cache formatted color strings
* lisp/org-latex-preview.el (org-latex-preview--format-color,
org-latex-preview--format-color-cache): Introduce a color cache alist, and use
it.
2024-04-01 19:43:19 +08:00
TEC 49dfec7d28
org-latex-preview: Reduce overhead in SVG editing
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor):
By setting the coding system and avoiding triggering any file
handlers (such as the `image-file-handler'), memory usage is nearly
halved, reducing GC pressure.
2024-04-01 19:43:19 +08:00
TEC cdb10837d0
org-latex-preview: Tweak baseline alignment
* lisp/org-latex-preview.el (org-latex-preview--update-overlay): After
doing quite a bit of testing, tweak the ascent formula to introduce a
slight correction to visually improve the final result.
2024-04-01 19:43:19 +08:00
TEC 76059dade0
org-latex-preview: Introduce dvipng filter
* lisp/org-latex-preview.el (org-latex-preview--dvipng-filter,
org-latex-preview-create-image-async): Introduce a dvipng filter
function to capture information from the dvipng stdout, and place images
as they are generated.
(org-latex-preview-process-alist): Update default dvipng process to emit
depth and height information.
2024-04-01 19:43:19 +08:00
TEC eb234e9467
org-latex-preview: Eagerly make fragment overlays
* lisp/org-latex-preview.el (org-create-latex-export,
org-latex-preview--place-images, org-latex-preview--generic-callback,
org-latex-preview--create-tex-file,
org-latex-preview-create-image-async, org-latex-preview--create,
org-latex-preview--close-previous-overlay,
org-latex-preview--make-overlay, org-latex-preview--update-overlay,
org-latex-preview-processing-face): Instead of saving buffer locations
and creating an overlay after the fragment image has been generated,
create an overlay initially and then update it when the image has been
created.  This is done by splitting the image-related code of
`org-latex-preview--make-overlay' into a new function,
`org-latex-preview--update-overlay'.  This provides a number of
advantages, primarily robustness to buffer edits during image
generation.  It also allows us to create a face to indicate
in-progress (`org-latex-preview-processing-face'), which is a nice
visual indicator.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 4213130bd9
org-latex-preview: Avoid duplicating cached images
* lisp/org-latex-preview.el (org-latex-preview--cache-image): When
caching an image, check if there is already an entry in the
`org-persist--index' with the same hash as this one.  This avoids
missing preview images for fragments with duplicates in a buffer, or
across org-persist's cache.  Without this measure, when we try to
register two fragments identified by the same hash,
`org-persist-register' returns a structure with the correct metadata
for both, but with the cached image path field missing for the second
fragment.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur d0be084eb0
org-latex-preview: Prioritise near latex previews
* lisp/org-latex-preview.el (org-latex-preview-fragments): Reorder
gathered latex fragments so that they are processed starting at the
window start position.  When previewing a large file, this makes a
significant difference to the perceived speed of the processing.
Remove references to `org-preview-latex-image-directory' from this
function, as it is no longer used to cache images.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur e9d505bda2
org-latex-preview: Avoid duplicate latex fragments
* lisp/org-latex-preview.el (org-latex-preview-collect-fragments): This
function was collecting duplicate org-elements when handling nested
latex environments (For instance, a matrix env inside an equation env).
Fix by comparing the current element with the previously collected one.
2024-04-01 19:43:19 +08:00
TEC 70c8b12187
org-latex-preview: Inhibit fsync when editing SVGs
* lisp/org-latex-preview.el (org-latex-preview--svg-make-fg-currentColor):
The value of fsync appears questionable at best on modern hardware, and
makes little sense for small files where the performance overhead is
significant.  Thus, it makes sense to inhibit fsync when editing the
generated SVGs.
2024-04-01 19:43:19 +08:00
Karthik Chikmagalur 56a312c03f
org-latex-preview: Add org-preview-latex-auto-mode
* lisp/org-latex-preview.el (org-latex-preview--make-overlay): Add
overlay hooks that correct for any edits made inside the overlay, and
store a copy of the image specification in the "preview-image" slot.
Also return the created overlay, so it can be used in other functions.
(org-latex-preview--from-overlay-p, org-latex-preview--marker,
org-latex-preview--inhibit): New variables to keep track of overlay
state when using auto-mode.
(org-latex-preview--handle-pre-cursor,
org-latex-preview--handle-post-cursor, org-latex-preview--move-into):
Detect when the cursor is entering or leaving a preview overlay, and
trigger the appropriate action.
(org-latex-preview--open-this-overlay,
org-latex-preview--close-previous-overlay): When cursor has entered/left
a preview overlay, show the text/image as appropriate.
(org-latex-preview--handle-insert): Create a dummy preview overlay when
a new LaTeX fragment is created.
(org-latex-preview--insert-front-handler,
org-preview--insert-behind-handler): Extend preview overlay boundaries
when their content changes.
(org-latex-preview-auto-mode): A new minor mode for automatic
opening/closing of preview overlays, and regeneration.
(org-latex-preview-auto-generate-p): Variable which affects the
regeneration behaviour of `org-latex-preview-auto-mode'.
2024-04-01 19:43:19 +08:00
TEC 4f25ae95c7
org-latex-preview: Use prefix more consistently
* lisp/ox-odt.el (org-odt--translate-latex-fragments): Use renamed
org-latex-preview-* functions/variables.

* lisp/ox-html.el (org-html-latex-fragment, org-html-latex-environment,
org-html-format-latex, org-html-with-latex): Use renamed
org-latex-preview-* functions/variables.

* lisp/org.el (org-compute-latex-and-related-regexp,
org-latex-packages-alist): Use renamed org-latex-preview-*
functions/variables.

* lisp/org-latex-preview.el (org-dvipng-color, org-create-formula-image,
org--get-display-dpi, org-create-latex-export,
org-preview-latex--tex-styled, org-preview-precompile,
org-latex-preview--place-images, org-latex-preview--generic-callback,
org-latex-preview--image-extract-async,
org-preview-latex--create-tex-file, org-create-formula-image-async,
org-create-latex-preview, org-format-latex, org-latex-preview-fragments,
org-latex-replace-fragments, org-latex-preview,
org--latex-preview-region, org-clear-latex-preview,
org-latex-preview--handle-insert,
org-latex-preview--close-previous-overlay,
org-latex-preview--handle-post-cursor, org--make-preview-overlay,
org-latex-preview-auto-generate-p, org-preview-use-precompilation,
org-format-latex-header, org-preview-latex-process-alist,
org-preview-latex-default-process, org-format-latex-signal-error,
org-format-latex-options): Use renamed org-latex-preview-*
functions/variables.  Use the org-latex-preview group instead of
org-latex for preview-related variables.

* lisp/org-compat.el: Add entries for renamed and obsoleted
org-latex-preview-* functions/variables.

* lisp/ob-latex.el (org-babel-execute:latex, org-format-latex-header)):
Use renamed org-latex-preview-* functions/variables.

* doc/org-manual.org (Footnotes, Previewing LaTeX fragments, LaTeX
fragments): Use renamed org-latex-preview-* functions/variables.

org-latex-preview: clear overlays name

* lisp/org-latex-preview.el (org-clear-latex-preview):
2024-04-01 19:43:19 +08:00
TEC 39a612cfb6
org-latex-preview: Basic error indication
* lisp/org-latex-preview.el (org-latex-preview--tex-compile-async,
org-latex-preview--latex-preview-filter): Search the latex compilation
stdout for fragment error messages via a process filter, and record any
found.
(org-latex-preview--display-info): Save the :error field of fragments.
(org--make-preview-overlay): When showing an SVG that has an error, use
the error face.
(org-preview-latex--tex-styled): Make any generated styling directives
take up exactly one line in all situations, so the fragment-relative
line numbers can easily be worked out in
`org-latex-preview--latex-preview-filter'.
2024-04-01 19:43:18 +08:00
TEC 4d2d6e2636
org-latex-preview: Filter dvisvgm process for info
* lisp/org-latex-preview.el (org-latex-preview--display-info,
org-latex-preview--cleanup-callback, org-create-formula-image-async,
org--make-preview-overlay): Apply a filter to the dvisvgm process in
order to place overlays as images are produced, and along the way
extract size and baseline information that is used to more accurately
position the overlay image.  Because `org-latex-preview--place-images'
is now run within a filter and hence the stdout buffer, we need to
record the org buffer and switch to it before placing overlays.
(org-latex-preview--image-extract-async): Record the DPI-based scaling
factor so it can be accounted for when calculating the pt-scale fragment
height/width/depth.
(org-latex-format-options): Introduce a new parameter :zoom for
affecting the display scaling of images with associated height
resolution, but unlike :scale not the resolution/size of the images
files themselves.  This is then used in `org--make-preview-overlay'.
2024-04-01 19:43:18 +08:00
TEC fcdb639abb
org-latex-preview: Use a fragment info plists
* lisp/org-latex-preview.el (org-latex-preview--cleanup-callback,
org-create-formula-image-async, org-create-latex-preview): Instead of
using lists of the same length for fragment information, use a single
list of fragment information plists.  This allows for more information
to be stored/used without ending up with half a dozen disparate lists
that we rely on lining up.
2024-04-01 19:43:18 +08:00
TEC c59b71fd65
org-latex-preview: Use org-persist for caching
* lisp/org-latex-preview.el
(org-latex-preview--cache-image, org-latex-preview--get-cached):
Implement image data save/retrieve functions using org-persist.
(org-place-latex-image, org-create-latex-export,
org-latex-preview--cleanup-callback, org-create-formula-image-async,
org-create-latex-preview, org--make-preview-overlay): Use the new model
of image data caching relying on org-persist.
2024-04-01 19:43:18 +08:00
Karthik Chikmagalur 5f144eb59f
org-latex-preview: Make image optional in overlay
* lisp/org-latex-preview.el (org-make--preview-overlay): Supplying an
image file when creating a latex preview overlay is now optional.
This change is in preparation for fully-automatic preview generation,
which requires "dummy" overlays to be placed on latex fragments that
have not yet been fully inserted or previewed.
2024-04-01 19:43:18 +08:00
Karthik Chikmagalur 4060cea8fc
org-latex-preview: Add imagemagick support
* lisp/org-latex-preview.el (org-preview-latex-process-alist,
org-preview-latex--create-tex-file, org-preview-precompile):
Add a new entry `:latex-precompiler' to
`org-preview-latex-process-alist', and tweak imagemagick-specific
`:image-converter' entries.  The function `org-preview-precompile' now
accepts two arguments.  Extra processing info is used to find the
right precompilation command.
2024-04-01 19:43:18 +08:00
TEC a063a68a87
org-macs: Rework async filter
* lisp/org-macs.el (org-async--filter, org-async-call): Expose :info to
the async filter function, and make the obvious modifications to the
process buffer content.
2024-04-01 19:43:18 +08:00
TEC 236d3fa185
org-macs: Accept nested org-async callbacks
* lisp/org-macs.el (org-async--execute-callback, org-async-call): Change
the org-async call arguments callback form to start with the symbol
org-async-task.  This allows for a list of callbacks to be
differentiated from a single callback.  `org-async-call' is also
extended to accept a a callback of this form as its sole argument.

* lisp/org-latex-preview.el (org-latex-preview--image-extract-async,
org-latex-preview--tex-compile-async, org-create-formula-image-async):
Use the new async callback form.
2024-04-01 19:43:18 +08:00
TEC 875bd0fdf8
org-latex-preview: use currentColor in SVGs
* lisp/org-latex-preview.el (org-place-latex-image,
org-create-formula-image-async, org--make-preview-overlay,
org-latex-preview--dvisvgm-callback): Edit the dvisvgm generated SVGs to
use "currentColor" instead of a hardcoded foreground color.  To then set
the color of the displayed images, set the overlay face as appropriate.
(org-create-latex-preview): Now that the foreground is generalised, when
producing the sha1 hash for an SVG image, the current foreground value
should not affect it.
2024-04-01 19:43:18 +08:00
TEC 97048011fa
org-latex-preview: Run dvipng concurrently
* lisp/org-latex-preview.el (org-create-formula-image-async): When using
dvipng with the "--follow" flag, image processing can occur
concurrently, so we may as well check for this case and start it
concurrently when this occurs.
2024-04-01 19:43:18 +08:00
TEC 3492e4ddeb
org-latex-preview: Refactor async formula function
* lisp/org-latex-preview.el (org-create-preview-string,
org-create-latex-preview, org-latex-replace-fragments,
org-create-formula-image-async): Refactor
`org-create-formula-image-async', specifically by splitting up the
texfile creation, texfile compilation, image extraction, and cleanup
phases into individual functions (`org-preview-latex--create-tex-file',
`org-latex-preview--tex-compile-async',
`org-latex-preview--image-extract-async',
`org-latex-preview--cleanup-callback') and use `org-async-call' for
managing async.  Along the way a few other minor tweaks have crept in.
2024-04-01 19:43:18 +08:00
Karthik Chikmagalur b17569579f
org-latex-preview: Add preamble precompilation
* lisp/org-latex-preview.el (org-create-formula-image-async): Change
how the latex header is computed to account for precompiled headers.
(org-preview-use-precompilation): Boolean to control if
header/preamble precompilation is enabled when generating latex
previews.  If enabled, previewing will be much faster at the expense
of a slower first run.
(org-preview-precompile): This function creates precompiled dumps of
latex preambles/headers, and is intended for use with
`org-create-formula-image-async'.
2024-04-01 19:43:18 +08:00
Karthik Chikmagalur ff16855fde
org-latex-preview: Change default latex command
* lisp/org-latex-preview.el (org-preview-latex-process-alist,
org-create-formula-image-async): Change the default latex command to
include the input file name.  Previously the input file was introduced
via process input for compatibility with preview.sty directives.  But
it appears that it's possible to simply set \RequirePackage{preview}
in the latex header without issues.
2024-04-01 19:43:18 +08:00
TEC dcfe13ee6c
org-latex-preview: Get face from char before latex
* lisp/org-latex-preview.el (org-create-latex-preview): Instead of
getting the face using `face-at-point' use `get-text-property' on the
position one before the start of the LaTeX fragment.  This ensures that
the face is that of the parent element rather than the LaTeX fragment.
2024-04-01 19:43:18 +08:00
Karthik Chikmagalur 8c9a8c587f
org-latex-preview: Add async image previews
* lisp/org-latex-preview.el (org-latex-preview-fragments): Collect and
send all fragments to be processed in a single pass.

(org-create-latex-preview): Apply cached previews and send the
other fragments to be generated asynchronously.

(org-create-formula-image-async): Generate latex preview
images asynchronously and apply them to the buffer.

(org-create-preview-string): Helper function that accepts a math
fragment and returns a latex snippet suitable for use with
preview.sty. Respects color preferences.
2024-04-01 19:43:18 +08:00
TEC cdd939c8ee
org-latex-preview: Collect math fragments in fun
* lisp/org-latex-preview.el (org-latex-preview-fragments,
org-latex-replace-fragments, org-latex-collect-fragments): Introduce a
new function to collect all LaTeX math fragments in a
region (`org-latex-collect-fragments') and use it in
`org-latex-preview-fragments' and `org-latex-replace-fragments'.
2024-04-01 19:43:18 +08:00
TEC 1d833bf3b6
org-latex-preview: Split org-create-latex-preview
* lisp/org-latex-preview.el (org-create-latex-preview,
org-create-latex-export): Split the export and preview functionality of
`org-create-latex-preview' into two functions: a rewritten
`org-create-latex-preview' that now /only/ deals with previews, and
`org-create-latex-export' for exports.
(org-latex-preview-fragments): Use the new `org-create-latex-preview`.
(org-latex-replace-fragments): Use the new `org-create-latex-export`.
2024-04-01 19:43:18 +08:00
TEC c4061260f3
org-latex-preview: Split org-format-latex into two
* lisp/org-latex-preview.el (org-format-latex, org-create-latex-preview,
org-latex-replace-fragments): The rather large `org-format-latex'
function mixed the preview and export code paths together in rather
confusing way.  This has now been split into
`org-latex-replace-fragments' for export, and
`org-latex-preview-fragments' for in-buffer previews.
(org--latex-preview-region): Replace `org-format-latex' with the more
specific `org-latex-preview-fragments'.
(org-latex-tentative-math-re): Instead of let-binding the math regexp,
use a const and explain its usage.

* lisp/ox-odt.el (org-odt--translate-latex-fragments): Replace
`org-format-latex' with the more specific `org-latex-replace-fragments`.

* lisp/ox-html.el (org-html-format-latex): Replace `org-format-latex'
with the more specific `org-latex-replace-fragments`.
2024-04-01 19:43:18 +08:00
TEC 8163f7e4fe
org-latex-preview: Split org-place-formula-image
* lisp/org-latex-preview.el (org-create-latex-preview,
org-place-formula-image, org-place-latex-image,
org-place-latex-image-link): Replace `org-place-formula-image' with two
functions, one for overlays (`org-place-latex-image') and another for
links (`org-place-latex-image-link').
2024-04-01 19:43:18 +08:00
TEC 9d4a259eca
org-latex-preview: Split org-format-latex into two
* lisp/org-latex-preview.el (org-create-latex-preview,
org-format-latex): Split `org-format-latex' into two, creating a new
function for the `cond' branch that deals with
`org-preview-latex-process-alist'.
2024-04-01 19:43:18 +08:00
TEC dadf491666
org.el: Relocate LaTeX preview code to new file
* lisp/org.el (org-format-latex-options, org-format-latex-signal-error,
org-latex-to-mathml-jar-file, org-latex-to-mathml-convert-command,
org-latex-to-html-convert-command, org-preview-latex-default-process,
org-preview-latex-process-alist, org-preview-latex-image-directory,
org-format-latex-header, org-format-latex-mathml-available-p,
org--make-preview-overlay, org-clear-latex-preview,
org--latex-preview-region, org-latex-preview, org-format-latex,
org-place-formula-image, org-create-math-formula,
org-format-latex-as-mathml, org-format-latex-as-html,
org--get-display-dpi, org-create-formula-image, org-dvipng-color,
org-dvipng-color-format, org-latex-color, org-latex-color-format,
org-normalize-color): Move to org-latex-preview.el.

* lisp/org-latex-preview.el: A new home for code related to the
generated of in-buffer previews of LaTeX fragments.
2024-04-01 19:43:15 +08:00
TEC 862bd572b3
ox-latex: Call compilation commands asynchronously
* lisp/ox-latex.el (org-latex-compile): Make use of the new
`org-async-call' to call compilation commands asynchronously.

When running ox-export via the command line, the expectation is the
Emacs process will not exit until the export has completed.  This
assumption is violated with async export, so when the current Emacs
session is `noninteractive' we go back to the previous (synchronously)
method of compiling.
2024-04-01 19:41:10 +08:00
TEC 93ee683097
org-macs: Add an async command execution system
* lisp/org-macs.el (org-async--stack, org-async--wait-queue,
org-async-process-limit, org-async-timeout,
org-async-check-timeout-interval, org-async--counter, org-async-call,
org-async--sentinel, org-async--cleanup-process,
org-async--execute-callback, org-async--monitor-scheduled,
org-async--monitor): Introduce an asynchronous command execution system.
2024-04-01 19:41:10 +08:00
TEC 45261a8530
---PATCH SET DIVIDER--- 2024-04-01 19:41:10 +08:00
TEC d6f9c3d80a
org-manual: Document export features
* doc/org-manual.org (+*** Export features): Initial manual entry on
export features.
2024-04-01 19:41:10 +08:00
TEC fc66891126
test-ox: Add tests for export feature resolution
* testing/lisp/test-ox.el: Add a set of tests for
`org-export-resolve-feature-implementations'.
2024-04-01 19:41:10 +08:00
TEC c9af8ffb1d
oc-*: Make use of conditional preamble for export
* lisp/oc-natbib.el (org-cite-natbib-use-package): Refactor to make use
of the conditional/generated preamble.

* lisp/oc-csl.el (org-cite-csl-finalizer): Refactor to make use of
the conditional/generated preamble.

* lisp/oc-biblatex.el (org-cite-biblatex-prepare-preamble): Refactor to
make use of the conditional/generated preamble.
2024-04-01 19:41:10 +08:00
TEC c007d681b6
ox: Introduce conditional/generated preamble
* lisp/ox.el (org-export-detect-features, org-export-expand-features,
org-export-generate-features-preamble): New functions for detecting
features and generating content based on them.
(org-export-conditional-features): Customisation for feature detection.
(org-export-as): Add detected to features to info in the slot :features.
(org-export-update-features): Add a convenience function for users to
edit the feature condition/implementation lists.
(org-export--annotate-info, org-export-detect-features,
org-export-define-derived-backend, org-export-define-backend,
org-export-conditional-features): Refactor backend feature
conditions/implementations into a struct field.  This allows for parent
inheritance to be properly managed, and leads into future work making
features more widely used in the export process.
(org-export-expand-features, org-export-resolve-feature-implementations,
org-export-generate-features-preamble,
org-export-expand-feature-snippets): The main functions for working with
export features.
(org-export-process-features, org-export-update-features): Introduce
`org-export-process-features' to simplify the application of features to
INFO.
2024-04-01 19:41:10 +08:00
TEC 0c715aceb8
org-compat: Add ensure-list as org-ensure-list
* lisp/org-compat.el (org-ensure-list): Add `ensure-list' from Emacs 28,
as `org-ensure-list'.
2024-04-01 19:41:10 +08:00
Max Nikulin a3bcb55365
test-org.el: Add new LaTeX to MathML tests for shell escaping
* testing/lisp/test-org.el (test-org/format-latex-as-html)
(test-org/create-math-formula): New tests for escaping of shell specials
in commands executed by `org-format-latex-as-html'
and `org-create-math-formula'.

These tests do not require applications for conversion of LaTeX
snippets and use simple shell commands instead.
2024-04-01 14:21:49 +03:00
Ihor Radchenko a698d073a1
org-latex-to-mathml/html-convert-command: Prevent shell expansion
* lisp/org.el (org-create-math-formula):
(org-format-latex-as-html): Shell-quote LaTeX fragment text when
replacing %i placeholder.  This prevents shell expansion of
$... and similar constructs inside the code.
(org-latex-to-mathml-convert-command):
(org-latex-to-html-convert-command): Update the docstring.
* etc/ORG-NEWS (~org-latex-to-mathml-convert-command~ and
~org-latex-to-html-convert-command~ shell-escape LaTeX code): Announce
the breaking change.
* doc/org-manual.org (LaTeX math snippets): Update example.

Reported-by: Max Nikulin <manikulin@gmail.com>
Link: https://orgmode.org/list/735645dd-1ddf-4579-a6dd-2700f3e83c94@gmail.com
2024-04-01 14:13:15 +03:00
Ihor Radchenko 1d86651bef
org--collect-keywords-1: Ignore #+SETUPFILE when its file handler errs
* lisp/org.el (org--collect-keywords-1): When `expand-file-name'
handler errs on #+SETUPFILE, ignore it.  An error may be thrown when
by custom file handler (for example, by TRAMP handler on GVFS path
when `tramp-gvfs-enabled' is nil; which is the default).

Reported-by: Max Nikulin <manikulin@gmail.com>
Link: https://orgmode.org/list/uue18j$j42$1@ciao.gmane.io
2024-04-01 14:04:50 +03:00
Ihor Radchenko 4c902d4771
doc/org-manual.org: Do not abbreviate links when editing the manual
Filling paragraphs depends on the hidden parts of the links, making
contributor edits dependent on the `org-link-descriptive'
customization.  Make filling consistent by not hiding link paths in
the org-manual.org specifically.
2024-04-01 12:55:52 +03:00
Ihor Radchenko 462bbb213a
Make sure that commented headings appear commented
* lisp/org.el (org-set-font-lock-defaults): Apply 'org-special-keyword
face to commented headings last, so that every markup inside look dim,
as per 'org-special-keyword face.
2024-03-31 14:50:49 +03:00
Ihor Radchenko d3878cb6fe
Consistently combine markup and the containing element faces during fontification
* lisp/org-src.el (org-fontify-inline-src-blocks-1):
* lisp/org.el (org-fontify-macros):
* lisp/org.el (org-activate-footnote-links):
(org-set-font-lock-defaults):  Prepend faces during
activation instead of overriding.  Add a comment explaining the
general rule how we combine faces.
* etc/ORG-NEWS (Org mode faces are now consistently combined, with
markup faces taking precedence over the containing element faces):
Document the breaking change.

Reported-by: StrawberryTea <look@strawberrytea.xyz>
Link: https://orgmode.org/list/875xy21e49.fsf@localhost
2024-03-31 14:41:07 +03:00
Ihor Radchenko c0e732266b
org-file-contents: Improve comment
* lisp/org.el (org-file-contents): Link to an example when
`file-remote-p' may throw an error.
2024-03-30 13:01:17 +03:00
Matthew Trzcinski e9c288dfac lisp/ob-comint.el: Fix prompt appearing in async shell results
* lisp/ob-comint.el (org-babel-comint-async-filter): Call prompt
`org-babel-comint--prompt-filter'

Reported-by: "Matthew Trzcinski" <matt@excalamus.com>
Link: https://list.orgmode.org/18d753c1e8a.cfb3e1921191837.5665565128507976741@excalamus.com/
2024-03-29 12:11:18 +01:00
Matthew Trzcinski 0102988afb testing/lisp/test-ob-shell.el: Test async prompt removal
* testing/lisp/test-ob-shell.el (test-ob-shell/session-async-results):
Create test verifying bug report that shell prompt appears in async
results.
2024-03-29 12:11:18 +01:00
Matthew Trzcinski 574e04d119 lisp/ob-comint.el: Refactor `org-babel-comint-with-output'
* lisp/ob-comint.el (org-babel-comint-with-output): Replace logic for
prompt and echo filtering with `org-babel-comint--prompt-filter' and
`org-babel-comint--echo-filter'.  Delete
`org-babel-comint-prompt-separator' variable and move related comment
to `org-babel-comint--prompt-filter'.
2024-03-29 12:11:18 +01:00
Matthew Trzcinski 3776eba2f7 lisp/ob-comint.el: Create comint echo filter
* lisp/ob-comint.el (org-babel-comint--echo-filter): Extract echo
filtering logic from `org-babel-comint-with-output' into a new
function.
2024-03-29 12:11:18 +01:00
Matthew Trzcinski c2b763dd14 testing/lisp/test-ob-comint.el: Make test for echo filter
* test-ob-comint.el:
(test-org-babel-comint/echo-filter-removes-echo): Test that echoed
input is removed from process buffer output.
2024-03-29 12:11:18 +01:00
Matthew Trzcinski 227cbb5359 lisp/ob-comint.el: Create comint prompt filter
* lisp/ob-comint.el (org-babel-comint--prompt-filter): Extract prompt
filtering logic from `org-babel-comint-with-output' into a new
function.
2024-03-29 12:11:18 +01:00
Matthew Trzcinski 820a99b171 testing/lisp/test-ob-comint.el: Make test for prompt filter
* test-ob-comint.el:  Make new file for comint tests.
(test-org-babel-comint/prompt-filter-removes-prompt): Test that the
prompt is removed from process buffer output.
2024-03-29 12:11:18 +01:00
Ross Timson 1be2f96931
lisp/ox-html.el: Add avif support for html export inline images
* lisp/ox-html.el (org-html-inline-image-rules): Add AVIF image
support for inline images on HTML export.

AVIF is well supported by browsers these days and offers similar
features and much better compression than the other image formats
commonly used for the web.

TINYCHANGE
2024-03-27 15:11:40 +03:00
Ihor Radchenko 3f20e32f8e
org-element-clock-parser: Do not be case-sensitive
* lisp/org-element.el (org-element-clock-parser): Fix demanding
upcased "CLOCK:" string.  As per general Org mode syntax principle,
keywords in Org mode are case-insensitive.
* testing/lisp/test-org-element.el (test-org-element/clock-parser):
Add test.

Reported-by: Gregor Zattler <telegraph@gmx.net>
Link: https://orgmode.org/list/875xx8mvvn.fsf@no.lan
2024-03-27 14:57:17 +03:00
Laurence Warne 990b89d324
Create commands for `org-read-date-minibuffer-local-map'
Create commands for `org-read-date-minibuffer-local-map' for use in
place of the inline lambda commands in order to aid user discoverability.

* org.el (org-calendar-goto-today-or-insert-dot)
(org-calendar-goto-today, org-calendar-backward-month)
(org-calendar-forward-month, org-calendar-backward-year)
(org-calendar-forward-year, org-calendar-backward-week)
(org-calendar-forward-week, org-calendar-backward-day)
(org-calendar-forward-day, org-calendar-view-entries)
(org-calendar-scroll-month-left, org-calendar-scroll-month-right)
(org-calendar-scroll-three-months-left)
(org-calendar-scroll-three-months-right): New functions.
* org-keys.el (org-read-date-minibuffer-local-map): Use the new
functions for keybindings instead of inline functions.

TINYCHANGE
2024-03-26 18:04:23 +03:00
Ihor Radchenko a3bd978e15
Merge branch 'bugfix' 2024-03-26 14:44:52 +03:00
Ihor Radchenko 6223f20a64
org-map-entries: Fix when buffer is not a file buffer and SCOPE is nil
* lisp/org.el (org-map-entries): Avoid triggering check for existence
of file on FS when SCOPE is nil.

Link: https://old.reddit.com/r/emacs/comments/1bnhz24/bug_nonexistent_agenda_file_s/
2024-03-26 14:36:53 +03:00
Ihor Radchenko f0a92b1eb9
org-resource-download-policy: Emphasize that the value of t is dangerous
* lisp/org.el (org-resource-download-policy): Mark value t in the
docstring dangerous.
2024-03-26 14:10:52 +03:00
Ihor Radchenko 9450468e5c
Merge branch 'bugfix' 2024-03-25 14:32:57 +03:00
Ihor Radchenko d7f7b63a77
lisp/org.el (untrusted-content): Fix for Emacs <29.3
* lisp/org.el (untrusted-content): Define the variable ourselves when
not defined by Emacs.
2024-03-25 14:32:09 +03:00
Ihor Radchenko 16f7021c75
Merge branch 'bugfix' 2024-03-25 13:56:53 +03:00
Ihor Radchenko 656531edbe
org-html-style-default: Fix XHTML validation failing
* lisp/ox-html.el (org-html-style-default): Provide mandatory
attribute type for style tag.

Reported-by: c.buhtz@posteo.jp
2024-03-25 13:54:58 +03:00
Ihor Radchenko 6652ee7be9
Merge branch 'bugfix' 2024-03-24 19:18:11 +03:00
Ihor Radchenko 5ff4d54c6f
Update version number for the 9.6.23 release 2024-03-24 19:16:02 +03:00
Ihor Radchenko 01f10031b1
org--confirm-resource-safe: Fix prompt when prompting in non-file Org buffers
* lisp/org.el (org--confirm-resource-safe): When called from
non-file buffer, do not put stray "f" in the prompt.
2024-03-24 17:11:36 +03:00
Ihor Radchenko 4255d5dcc0
org-file-contents: Consider all remote files unsafe
* lisp/org.el (org-file-contents): When loading files, consider all
remote files (like TRAMP-fetched files) unsafe, in addition to URLs.
2024-03-24 17:11:28 +03:00
Ihor Radchenko 03635a3355
org-latex-preview: Add protection when `untrusted-content' is non-nil
* lisp/org.el (org--latex-preview-when-risky): New variable
controlling how to handle LaTeX previews in Org files from untrusted
origin.
(org-latex-preview): Consult `org--latex-preview-when-risky' before
generating previews.

This patch adds a layer of protection when LaTeX preview is requested
for an email attachment, where `untrusted-content' is set to non-nil.
2024-03-24 17:11:17 +03:00
Ihor Radchenko 003ddacf1c
org-macro--set-templates: Prevent code evaluation
* lisp/org-macro.el (org-macro--set-templates): Get rid of any
risk to evaluate code when `org-macro--set-templates' is called as a
part of major mode initialization.  This way, no code evaluation is
ever triggered when user merely opens the file or when
`mm-display-org-inline' invokes Org major mode to fontify mime part
preview in email messages.
2024-03-24 17:11:05 +03:00
Ihor Radchenko 33503445e6
org-export: Do not treat unpaired ' and " as smart quotes
* lisp/ox.el (org-export--smart-quote-status): When quotes are not
balanced, treat " literally and ' as apostrophes.
* testing/lisp/test-ox.el (test-org-export/activate-smart-quotes): Fix
test with unbalanced " and add new tests for unbalanced quotes.

Reported-by: Juan Manuel Macías <maciaschain@posteo.net>
Link: https://list.orgmode.org/orgmode/875xxfqdpt.fsf@posteo.net/
2024-03-24 12:53:11 +03:00
Ihor Radchenko 8507efa848
Merge branch 'bugfix' 2024-03-23 17:22:39 +03:00
Nick Dokos 01b540e21f
org-manual: Add footnote on how to enable described functionality
* doc/manual.org (Literal Examples): The functionality of having
`ref:' links remote-highlighted in HTML is disabled by default (since
version 9.5).  Add a footnote to explain how to enable it.

Link: https://emacs.stackexchange.com/questions/80783/org-mode-export-to-html-onmouseover-highlighting-of-referenced-code-lines
2024-03-23 17:21:12 +03:00
Aaron L. Zeng 5808155084 lisp/ob-shell.el: Initialize explicit-shell-file-name
* lisp/ob-shell.el (org-babel-shell-initialize): force blocks to
always use the specified shell language

Sessions are initialized using `shell'.  The `shell' command checks
`explicit-shell-file-name' for file to use before checking other
variables, like `shell-file-name'.  Previously, only `shell-file-name'
was set.  So, if the user had set the `explicit-shell-file-name',
session blocks would use that whereas non-session blocks would use
`shell-file-name', resulting in inconsistent behavior.  This change
sets both variables so that even if the user changes the
`explicit-shell-file-name' or `shell-file-name', blocks will only use
the shell language specified by the block.

TINYCHANGE
2024-03-23 08:57:18 +01:00
Matthew Trzcinski 34c844ab33 Revert "lisp/ob-shell.el: Initialize explicit-shell-file-name"
This reverts commit 37cd00bb12.

Commit 37cd00bb accidentally added check.sh, nohup.out, and setup.sh.
2024-03-23 08:54:51 +01:00
Ihor Radchenko 13af0fd543
fixup! Support completion boundaries when completing olp, tags, and agenda filter
Copy-paste typos.
2024-03-23 08:58:20 +03:00
Ihor Radchenko 5fa0f0c6fe
Support completion boundaries when completing olp, tags, and agenda filter
* lisp/org-agenda.el (org-agenda-filter-completion-function):
* lisp/org-refile.el (org-olpath-completing-read):
* lisp/org-tags.el (org-tags-completion-function): Add support for
orderless/flex completion styles that require boundaries operation.
2024-03-22 13:50:45 +03:00
Ihor Radchenko 50c51b9ad1
Update version number for the 9.6.22 release 2024-03-22 10:30:04 +03:00
Ihor Radchenko 01cc01fc13
doc/org-manual.org (Using the Property API): Fix typo 2024-03-21 17:12:58 +03:00
Ihor Radchenko 1b99cccbe9
Merge branch 'bugfix' 2024-03-21 15:56:36 +03:00
Ihor Radchenko 5dbf930c2d
org-agenda-clock-cancel: Unmark clocking tasks in the agenda buffer
* lisp/org-agenda.el (org-agenda-clock-cancel): When canceling clock,
remove clocking overlays from current agenda buffer.
2024-03-21 15:55:21 +03:00
Ihor Radchenko 81dcc6350f
Merge branch 'bugfix' 2024-03-21 12:13:38 +03:00
Ihor Radchenko fe83afc300
org-persist: Do not demand write access to existing directories
* lisp/org-persist.el (org-persist--check-write-access): New function
checking write access to creating a directory and all the necessary
parents.  The function is a refactoring of duplicated code that
previously checked one parent beyond what needs to be created.
(org-persist-write:index): Use the new function.  Create
`org-persist-directory' together with all its parents.  Gracefully
handle failure.
* lisp/org-persist.el: Use the new function when adding hooks to
`kill-emacs-hook'.

Reported-by: Al Oomens <aloomens@outlook.com>
Link: https://list.orgmode.org/MW4PR19MB6888F37194BA260AE5631770C4332@MW4PR19MB6888.namprd19.prod.outlook.com
2024-03-21 12:13:13 +03:00
Ihor Radchenko ad02825337
org-persist: Do not demand write access to existing directories
* lisp/org-persist.el (org-persist--check-write-access): New function
checking write access to creating a directory and all the necessary
parents.  The function is a refactoring of duplicated code that
previously checked one parent beyond what needs to be created.
(org-persist-write:index): Use the new function.  Create
`org-persist-directory' together with all its parents.  Gracefully
handle failure.
* lisp/org-persist.el: Use the new function when adding hooks to
`kill-emacs-hook'.

Reported-by: Al Oomens <aloomens@outlook.com>
Link: https://list.orgmode.org/MW4PR19MB6888F37194BA260AE5631770C4332@MW4PR19MB6888.namprd19.prod.outlook.com
2024-03-21 12:04:53 +03:00
Ihor Radchenko 224254e7f0
fixup! Fix org-fontify-quote-and-verse-blocks when org-src-fontify-natively is t 2024-03-19 23:35:30 +03:00
Ihor Radchenko df4a48bc4f
Fix org-fontify-quote-and-verse-blocks when org-src-fontify-natively is t
* lisp/org.el (org-fontify-meta-lines-and-blocks-1): Do not attempt
native fontification in quote and verse blocks when
`org-src-fontify-natively' is non-nil.  Limit native fontification to
src and example blocks only.

Reported-by: William Denton <william@williamdenton.org>
Link: https://orgmode.org/list/Ml33lIeToTUsXIzeVEIolD5SsK-HJ0yrdPgOMr2N9WrldhU72LtjnGjehgViKAjMOgN5IAwM5Tx5TfCJlRBrTfnGnxqpuhy3-lEbUNycPMY=@williamdenton.org
2024-03-19 22:22:57 +03:00
Ihor Radchenko 4f548f9482
fixup! org-create-math-formula: Do not run file-related hooks when checking output 2024-03-19 19:26:46 +03:00
Ihor Radchenko b338a90698
org-create-math-formula: Do not run file-related hooks when checking output
* lisp/org.el (org-create-math-formula): Avoid using
`find-file-noselect' to check contents of the generated mathml
formula.  `find-file-noselect' runs a number of hooks, which are not
necessary and may sometimes throw errors.

Link: https://orgmode.org/list/ut96a7$i6d$1@ciao.gmane.io
2024-03-19 17:44:00 +03:00
Damien Cassou 2381c7b882
ox-odt: Avoid warning when everything is fine
* lisp/ox-odt.el (org-odt--translate-latex-fragments): When
processing-type is already 'verbatim, no need to print any warning.
2024-03-19 17:22:52 +03:00
Ihor Radchenko 63b10621a0
org-sparse-tree: Fix matching property names containing "-"
* lisp/org.el (org-sparse-tree): Escape "-" in property names.

Reported-by: Fabian Kurmann <fabian.kurmann@uni-duesseldorf.de>
Link: https://orgmode.org/list/87v87qprwq.fsf@localhost
2024-03-19 17:02:02 +03:00
Leo Butler 46909a54e1
testing/lisp/test-ox-beamer.el: New regression tests for ox-beamer.
* testing/lisp/test-ox-beamer.el (ox-beamer/orgframe,
ox-beamer/orgframe-in-example, ox-beamer/orgframe-in-one-example): New
file.  Regression tests for ox-beamer.  Test that the
`org-beamer-frame-environment' is defined only when used.
2024-03-17 17:35:38 +03:00
Leo Butler 80615195c4
lisp/ox-beamer.el: constrain use of org-beamer-frame-environment
* lisp/ox-beamer.el (org-beamer--format-frame, org-beamer-template):
Only use `org-beamer-frame-environment' when a frame is marked as
fragile and the frame's contents include either \begin{frame} or
\end{frame}.  When `org-beamer-frame-environment' is used and not
equal to "frame", add the property :beamer-define-frame to INFO and
set it to t.  When that property is t, `org-beamer-template' emits a
definition of the alternative frame environment.

Refs: https://list.orgmode.org/orgmode/87bk7jeik8.fsf@localhost/
https://list.orgmode.org/87a5nux3zr.fsf@t14.reltub.ca/T/
2024-03-17 17:35:37 +03:00
Ihor Radchenko aa241ffd0b
Makefile: List make native in make help output 2024-03-17 17:35:37 +03:00
Aaron L. Zeng 37cd00bb12 lisp/ob-shell.el: Initialize explicit-shell-file-name
* lisp/ob-shell.el (org-babel-shell-initialize): force blocks to
always use the specified shell language

Sessions are initialized using `shell'.  The `shell' command checks
`explicit-shell-file-name' for file to use before checking other
variables, like `shell-file-name'.  Previously, only `shell-file-name'
was set.  So, if the user had set the `explicit-shell-file-name',
session blocks would use that whereas non-session blocks would use
`shell-file-name', resulting in inconsistent behavior.  This change
sets both variables so that even if the user changes the
`explicit-shell-file-name' or `shell-file-name', blocks will only use
the shell language specified by the block.

TINYCHANGE
2024-03-17 13:42:39 +01:00
Matthew Trzcinski cb80019c28 Revert "lisp/ob-shell.el: Initialize explicit-shell-file-name"
This reverts commit 0e2a9524dc.
2024-03-17 13:40:57 +01:00
Ihor Radchenko d545ad6068
lisp/ol.el: Make `org-link-get-parameter' a valid PLACE for `setf'
* lisp/ol.el (org-link-get-parameter): Define setter.  This allows
modifying link parameters with `setf' and altering them via
`add-function'.

Link: https://orgmode.org/list/a123389c-8f86-4836-a4fe-1e3f4281d33b@app.fastmail.com
2024-03-17 13:06:11 +03:00
Ihor Radchenko ae50b94e0e
Merge branch 'bugfix' 2024-03-16 16:03:00 +03:00
Jan Zavitski c5ede53210
org-export-dictionary: Improve Estonian translation
* lisp/ox.el (org-export-dictionary): Add missing and improve
existing Estonian translation entries.
2024-03-16 16:02:14 +03:00
Visuwesh 89b0773c3f
ob-calc.el: Add support for tables in Calc source block :var
A table with MxN dimensions is converted to a MxN matrix when given in
:var to a Calc source block.  A table with a single row is converted
to a vector (i.e., row vector).

* lisp/ob-calc.el (org-babel-execute-src-block:calc): Construct the
right data structure to pass tables as matrices to Calc.
* testing/lisp/test-ob-calc.el: Add tests for ob-calc, and this new
feature.
* etc/ORG-NEWS: Announce the feature.
* mk/default.mk (BTEST_OB_LANGUAGES): Enable ob-calc tests by default.
2024-03-16 15:15:40 +03:00
Ihor Radchenko a862ef6906
etc/ORG-NEWS: Fix typo 2024-03-16 14:31:14 +03:00
Ihor Radchenko caafed42e5
Merge branch 'bugfix' 2024-03-16 12:26:27 +03:00
Ihor Radchenko 712ef988c3
org-fold-core-region: Fix removing non-fold overlays
* lisp/org-fold-core.el (org-fold-core-region): Do not clear all the
overlays in region when unfolding and when SPEC-OR-ALIAS is nil.

Reported-by: Bruno Barbier <brubar.cs@gmail.com>
Link: https://orgmode.org/list/65f4a408.df0a0220.5debf.2c65@mx.google.com
2024-03-16 12:26:00 +03:00
Ihor Radchenko 8b73c8b98f
org-fold-core-region: Fix removing non-fold overlays
* lisp/org-fold-core.el (org-fold-core-region): Do not clear all the
overlays in region when unfolding and when SPEC-OR-ALIAS is nil.

Reported-by: Bruno Barbier <brubar.cs@gmail.com>
Link: https://orgmode.org/list/65f4a408.df0a0220.5debf.2c65@mx.google.com
2024-03-16 12:23:08 +03:00
Ihor Radchenko 9f4064e68e
org-capture-templates: Document %^{prompt}X %-escape syntax
* lisp/org-capture.el (org-capture-templates):
* doc/org-manual.org (Template expansion): Document the supported
custom prompt syntax.

Link: https://old.reddit.com/r/orgmode/comments/1bfgzsz/format_timestamp_after_capture_by_prompt/
2024-03-16 12:18:17 +03:00
Ihor Radchenko acf6fa6209
org-fold-core--property-symbol-get-create: Improve performance
* lisp/org-fold-core.el (org-fold-core--property-symbol-get-create):
Cache values of global property symbols.
2024-03-16 12:17:49 +03:00
Ihor Radchenko 051e7b9d7c
Reduce repetitive calls to `find-buffer-visiting' + `find-file-noselect'
* lisp/org-macs.el (org-with-file-buffer): New macro switching to a
file buffer temporarily and killing it if a buffer visiting file did
not exist previously.
(org-file-buffer-created): New variable set when buffer visiting file
has been created.
* lisp/ob-tangle.el (org-babel-tangle-file):
* lisp/org-archive.el (org-archive-subtree):
* lisp/org-refile.el (org-refile):
(org-refile-check-position):
(org-refile-new-child):
* lisp/ox-org.el (org-org-publish-to-org):
* lisp/ox-publish.el (org-publish-org-to):
(org-publish-find-property): Avoid calling `find-buffer-visiting' +
`find-file-noselect'.  The latter calls the former.  Instead, either
just call `find-file-noselect' or use `org-with-file-buffer'.

This commit addresses O(N_buffers) complexity in
`find-buffer-visiting', reducing the number of calls to it.

See Emacs bug#66117.
2024-03-16 11:21:30 +03:00
Matthew Trzcinski 0e2a9524dc lisp/ob-shell.el: Initialize explicit-shell-file-name
* lisp/ob-shell.el (org-babel-shell-initialize): force blocks to
always use the specified shell language

Sessions are initialized using `shell'.  The `shell' command checks
`explicit-shell-file-name' for file to use before checking other
variables, like `shell-file-name'.  Previously, only `shell-file-name'
was set.  So, if the user had set the `explicit-shell-file-name',
session blocks would use that whereas non-session blocks would use
`shell-file-name', resulting in inconsistent behavior.  This change
sets both variables so that even if the user changes the
`explicit-shell-file-name' or `shell-file-name', blocks will only use
the shell language specified by the block.

Submitted by: "Aaron L. Zeng" me@bcc32.com

TINYCHANGE
2024-03-15 22:27:04 +01:00
Ihor Radchenko fb61e83f2a
org-insert-property-drawer: Fix incorrect fold type
* lisp/org.el (org-insert-property-drawer): When folding style is
overlays, do not use outline folds to fold the property drawer.

Reported-by: Bruno Cardoso <cardoso.bc@gmail.com>
Link: https://orgmode.org/list/87wmq5btzn.fsf@gmail.com
2024-03-15 00:20:02 +03:00
Ihor Radchenko 7653e58f6d
org-table-next-row: Improve docstring
* lisp/org-table.el (org-table-next-row): Explain what happens when
the next row is outside table or when it is an hline.

Link: https://orgmode.org/list/B35D543F-6A6C-4F7D-913F-E8CBB6B9BC1B@gmail.com
2024-03-13 17:14:04 +03:00
Stefan Monnier 2773904cfb
org-src-font-lock-fontify-block: Clarify offset computation
* lisp/org-src.el (org-src-font-lock-fontify-block): Improve the translation
of local positions into org-buffer positions, and get rid of
assumption about the value of `point-min' while we're at it.
2024-03-13 16:31:56 +03:00
Ihor Radchenko cd0568ab1b
org-submit-bug-report: Submit Org-related warnings
* lisp/org.el (org--warnings): New variable storing Org mode warnings
to be submitted together with bug reports.
(org-submit-bug-report): Add `org--warnings' to bug report template.
* lisp/org-element.el (org-element--cache-warn): Store cache warnings
for submission.
2024-03-13 16:07:06 +03:00
Max Nikulin ca29290948
testing: Add missing lexical-binding modeline
* testing/lisp/test-ox-html.el:
* testing/lisp/test-ox-texinfo.el: Add modeline with `lexical-binding'.
2024-03-13 15:35:32 +03:00
Max Nikulin ff5fc2563f
testing: Fix misleading file headers
* testing/lisp/test-org-tempo.el:
* testing/lisp/test-property-inheritance.el: Do not refer to
non-existing file names in the file header.
2024-03-13 15:35:31 +03:00
Max Nikulin 37a98d7de4
testing: Fix file names in file headers
* testing/lisp/test-ob-julia.el:
* testing/lisp/test-ol-bbdb.el:
* testing/lisp/test-org-fold.el:
* testing/lisp/test-ox-ascii.el: Fix names in file headers.

Inconsistency was likely caused by copy-paste.
2024-03-13 15:35:30 +03:00
Ihor Radchenko 505db97a8c
org-update-parent-todo-statistics: Fix infinite loop after 4254a54f8
* lisp/org.el (org-update-parent-todo-statistics): Make sure that we
move to the end of updated cookie at the end of search loop, even when
the cookie has not been updated.

Reported-by: No Wayman <iarchivedmywholelife@gmail.com>
Link: https://orgmode.org/list/87le6pucnv.fsf@gmail.com
2024-03-13 13:26:00 +03:00
Gerard Vermeulen e2caccfdf6
lisp/oc-basic.el: add missing function declarations 2024-03-12 16:17:09 +03:00
Ihor Radchenko f08174a459
org-export: Display a warning when the value of :exports header arg is invalid
* lisp/ob-exp.el (org-babel-exp-do-export): Display warning when
:exports value is not known.  Document nil return value.
(org-babel-exp-process-buffer): Do not remove code block when
`org-babel-exp-do-export' returns nil.

Reported-by: Max Nikulin <manikulin@gmail.com>
Link: https://orgmode.org/list/usc9jn$g2r$1@ciao.gmane.io
2024-03-12 16:07:13 +03:00
Ihor Radchenko c9b655f273
org-activate-folds: Skip over folded newlines faster
* lisp/org.el (org-activate-folds): When searching next unfolded
newline skip over folded newlines faster, using org-fold-core API.
2024-03-12 15:40:37 +03:00
Psionik K b6f8078ab4
org-do-remove-indentation: Ignore invisible text
* lisp/org-macs.el (org-do-remove-indentation): Set
`buffer-invisibility-spec' to nil before detecting the column or
moving to a column.

This fixes src_block indentation removal for org-modern-mode but will
also correct other cases of hidden indentation.

TINYCHANGE
2024-03-12 15:19:50 +03:00
Ihor Radchenko a1b8554f6f
org-mks: Do not leave window around
* lisp/org-macs.el (org-mks): Make sure that selection window is
closed upon exiting.  See also fef873b1c.

Reported-by: Björn Bidar <bjorn.bidar@thaodan.de>
Link: https://orgmode.org/list/874jdg2ipo.fsf@
2024-03-12 15:12:42 +03:00
Ihor Radchenko 72b0e9ff04
org-export: Do not strip link type by default during export
* lisp/ox-html.el (org-html-link):
* lisp/ox-latex.el (org-latex-link):
* lisp/ox-man.el (org-man-link):
* lisp/ox-md.el (org-md-link):
* lisp/ox-odt.el (org-odt-link--inline-image):
* lisp/ox-texinfo.el (org-texinfo-link): Preserve link type during
export for all the links, not just for a hard-coded subset.
* etc/ORG-NEWS (Built-in HTML, LaTeX, Man, Markdown, ODT, and Texinfo
exporters preserve the link protocol during export): Document the
breaking change.

Link: https://list.orgmode.org/orgmode/878r9nofpw.fsf@localhost/
2024-03-12 13:57:47 +03:00
Stefan Monnier b0c3c90574
ox-texinfo:: Always provide a @direntry
Until now @dircategory/@direntry entries were added only if
both TEXINFO_DIR_CATEGORY and TEXINFO_DIR_TITLE were set.
And the setting of TEXINFO_DIR_TITLE had to be careful to
provide exactly the right syntax.

This patch changes various things in this regard:
- Always generate a @dircategory/@direntry.
- Default TEXINFO_DIR_CATEGORY to "Misc".
- Use the document title by default if TEXINFO_DIR_DESC is missing.
- Rename TEXINFO_DIR_TITLE to TEXINFO_DIR_NAME.
- Use the filename by default when TEXINFO_DIR_NAME is missing.
- Try and make it harder to provide a direntry that does not
  have the right format or refers to a different filename than
  the one we're outputting to.

* lisp/ox-texinfo.el (texinfo): Add entry for TEXINFO_DIR_NAME.
(org-texinfo-template): Use sane defaults for `@direntry` and `@dircategory`.

* doc/org-manual.org (Texinfo specific export settings): Adjust accordingly.
(Info directory file, A Texinfo example, Export Setup): Update examples
to use the new syntax.
* etc/ORG-NEWS (Version 9.7 / New features): Add entry.
2024-03-08 13:45:26 +03:00
Stefan Monnier 4fd8691941
lisp/ox-texinfo.el: Remove redundant `:group`s 2024-03-08 13:45:25 +03:00
Ihor Radchenko 28dc5dd1ac
Update version number for the 9.6.21 release 2024-03-08 11:34:42 +03:00
58 changed files with 7789 additions and 1691 deletions

View File

@ -27,6 +27,7 @@ help helpall::
$(info make all - ditto)
$(info make compile - build Org ELisp files)
$(info make single - build Org ELisp files, single Emacs per source)
$(info make native - build Org natively compiled Elisp files)
$(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)

View File

@ -2,6 +2,7 @@
#+subtitle: Release {{{version}}}
#+author: The Org Mode Developers
#+language: en
#+startup: literallinks
#+texinfo: @insertcopying
@ -8281,6 +8282,12 @@ given here:
Prompt the user for a value for property {{{var(PROP)}}}. You may
specify a default value with =%^{PROP|default}=.
- =%^{PROMPT}X=, X is one of g,G,t,T,u,U,C,L ::
Prompt the user as in =%^X=, but use the custom prompt string. You
may specify a default value and completions with
=%^{PROMPT|default|completion1|completion2|completion3...}X=.
- =%^{PROMPT}= ::
Prompt the user for a string and replace this sequence with it. You
@ -11364,7 +11371,7 @@ pretty output for a number of export backends.
:END:
#+cindex: @LaTeX{} fragments
#+vindex: org-format-latex-header
#+vindex: org-latex-preview-header
Org mode can contain LaTeX math fragments, and it supports ways to
process these for several export backends. When exporting to LaTeX,
the code is left as it is. When exporting to HTML, Org can use either
@ -11421,20 +11428,19 @@ lines:
:END:
#+cindex: @LaTeX{} fragments, preview
#+vindex: org-preview-latex-default-process
#+vindex: org-latex-preview-process-default
If you have a working LaTeX installation and =dvipng=, =dvisvgm= or
=convert= installed[fn:38], LaTeX fragments can be processed to
produce images of the typeset expressions to be used for inclusion
while exporting to HTML (see [[*LaTeX fragments]]), or for inline
previewing within Org mode.
#+vindex: org-format-latex-options
#+vindex: org-format-latex-header
You can customize the variables ~org-format-latex-options~ and
~org-format-latex-header~ to influence some aspects of the preview.
In particular, the ~:scale~ (and for HTML export, ~:html-scale~)
property of the former can be used to adjust the size of the preview
images.
#+vindex: org-latex-preview-appearance-options
#+vindex: org-latex-preview-header
You can customize the variables ~org-latex-preview-appearance-options~ and
~org-latex-preview-header~ to influence some aspects of the preview.
In particular, the ~:scale~ and ~:zoom~ properties of the former can
be used to adjust the size of the preview images.
- {{{kbd(C-c C-x C-l)}}} (~org-latex-preview~) ::
#+kindex: C-c C-x C-l
@ -11458,6 +11464,24 @@ To disable it, simply use
: #+STARTUP: nolatexpreview
#+vindex: org-latex-preview-numbered
When generating previews, Org mode can track equation numbers and keep
them consistent by regenerating previews when necessary. This
behavior is controlled by the variable ~org-latex-preview-numbered~.
Org mode can automatically preview LaTeX fragments as you type them,
and hide and reveal preview images as the cursor moves into or out of
them. To enable this, turn on the minor mode
~org-latex-preview-auto-mode~.
- (~org-latex-preview-auto-mode~) ::
#+findex: org-latex-preview-auto-mode
Generate previews of LaTeX fragments as they are entered in the
buffer. Previews will be generated when there is any change to the
buffer that includes the insertion of a LaTeX environment or
fragment.
*** Using CDLaTeX to enter math
:PROPERTIES:
:DESCRIPTION: Speed up entering of formulas.
@ -11617,9 +11641,12 @@ to determine the starting line number.
In literal examples, Org interprets strings like =(ref:name)= as
labels, and use them as targets for special hyperlinks like
=[[(name)]]=---i.e., the reference name enclosed in single parenthesis.
In HTML, hovering the mouse over such a link remote-highlights the
corresponding code line, which is kind of cool.
=[[(name)]]=---i.e., the reference name enclosed in single
parentheses. In HTML, hovering the mouse over such a link
remote-highlights the corresponding code line[fn:: This requires some
Javascript which is /not/ automatically included in the HTML output:
you have to customize the variable =org-html-head-include-scripts= to
~t~ to have it included (it is ~nil~ by default).], which is kind of cool.
You can also add a =-r= switch which /removes/ the labels from the
source code[fn:: Adding =-k= to =-n -r= /keeps/ the labels in the
@ -15167,7 +15194,7 @@ document in one of the following ways:
#+begin_src emacs-lisp
(setq org-latex-to-mathml-convert-command
"latexmlmath \"%i\" --presentationmathml=%o")
"latexmlmath %i --presentationmathml=%o")
#+end_src
To quickly verify the reliability of the LaTeX-to-MathML
@ -15718,17 +15745,26 @@ the general options (see [[*Export Settings]]).
- =TEXINFO_DIR_CATEGORY= ::
#+cindex: @samp{TEXINFO_DIR_CATEGORY}, keyword
The directory category of the document.
The directory category of the document. Defaults to ~Misc~.
- =TEXINFO_DIR_TITLE= ::
- =TEXINFO_DIR_NAME= ::
#+cindex: @samp{TEXINFO_DIR_TITLE}, keyword
The directory title of the document.
#+cindex: @samp{TEXINFO_DIR_NAME}, keyword
The directory name of the document.
This is the short name under which the ~m~ command will find your
manual in the main Info directory. It defaults to the base name of
the Texinfo file.
The full form of the Texinfo entry is ~* DIRNAME: NODE.~ where ~NODE~
is usually just ~(FILENAME)~. Normally this option only provides the
~DIRNAME~ part, but if you need more control, it can also be the full
entry (recognized by the presence of parentheses or a leading ~* ~).
- =TEXINFO_DIR_DESC= ::
#+cindex: @samp{TEXINFO_DIR_DESC}, keyword
The directory description of the document.
Defaults to the title of the document.
- =TEXINFO_PRINTED_TITLE= ::
@ -15812,11 +15848,11 @@ Copyright information is printed on the back of the title page.
#+cindex: @code{install-info}, in Texinfo export
#+cindex: @samp{TEXINFO_DIR_CATEGORY}, keyword
#+cindex: @samp{TEXINFO_DIR_TITLE}, keyword
#+cindex: @samp{TEXINFO_DIR_NAME}, keyword
#+cindex: @samp{TEXINFO_DIR_DESC}, keyword
The end result of the Texinfo export process is the creation of an
Info file. This Info file's metadata has variables for category,
title, and description: =TEXINFO_DIR_CATEGORY=, =TEXINFO_DIR_TITLE=,
title, and description: =TEXINFO_DIR_CATEGORY=, =TEXINFO_DIR_NAME=,
and =TEXINFO_DIR_DESC= keywords that establish where in the Info
hierarchy the file fits.
@ -15824,7 +15860,7 @@ Here is an example that writes to the Info directory file:
#+begin_example
,#+TEXINFO_DIR_CATEGORY: Emacs
,#+TEXINFO_DIR_TITLE: Org Mode: (org)
,#+TEXINFO_DIR_NAME: Org Mode
,#+TEXINFO_DIR_DESC: Outline-based notes management and organizer
#+end_example
@ -16232,7 +16268,7 @@ Texinfo code.
,#+TEXINFO_HEADER: @syncodeindex pg cp
,#+TEXINFO_DIR_CATEGORY: Texinfo documentation system
,#+TEXINFO_DIR_TITLE: sample: (sample)
,#+TEXINFO_DIR_NAME: sample
,#+TEXINFO_DIR_DESC: Invoking sample
,#+TEXINFO_PRINTED_TITLE: GNU Sample
@ -16771,6 +16807,378 @@ user-friendly improvements. See
<https://orgmode.org/worg/dev/org-export-reference.html> for more
details.
*** Export features
**** The underlying idea
Across export backends it is common to want to include certain chunks
of content that are only relevant in particular situations.
With static export templates, one is forced to choose between
including everything that /might/ be wanted, or including very little
by default and requiring common content to be manually added every
time it is wanted.
"Export features" allow for a third option, a much more sophisticated
method of resolving this dilemma. At the start of the export process,
the buffer being exported and the export communication plist (~info~)
are scanned to determine which capabilities are relevant to the
current export. During the construction of the final output this list
of capabilities is used to produce snippets of content to be included.
This can be thought of as the construction of a graph between conditions,
features, and feature implementations. For example, say we have three conditions
we want to support:
+ Say that images need some extra setup to be supported well, we can
just include it when image links are found in the buffer.
+ Say we can better support emojis by treating them as images in a
particular export backend. We could look for a signal in the buffer
that emojis should be handled as images, and then make use of some
"image support" and "emoji support" snippets.
+ Say that LaTeX maths requires some extra setup, we can just
do this when inline LaTeX fragments are found.
This situation can be crudely drawn with the following graph:
#+begin_example
condition feature implementation
========= ======= ===============
[emoji] -----------> emoji ------> [emoji plist]
\
'---->----.
\
[image link] ------> image ------> [image plist]
[inline LaTeX] ----> maths ------> [maths plist]
\____________________/ \__________________/
phase 1 phase 2
#+end_example
In phase 1 "feature detection" the relevant features are determined, and in
phase 2 "feature implementation" how those features can be provided is worked
out.
**** Feature detection
After the expansion of =#+include= statements and the removal of
comments, the export communication plist (~info~) is annotated. At the
very end of the annotation process, ~org-export-detect-features~ is
run to determine the list of capabilities relevant to the current export.
This operates by merging the global feature condition alist
(~org-export-conditional-features~) with the ~feature-conditions~ slot
of the current backend and each of its parents. This produces the
total feature conditions alist, which has the form:
#+begin_example
((condition . implied-features)
...)
#+end_example
Where =condition= is a test that implies that =implied-features= are
relevant. While =implied-features= is always a list of feature
symbols, for convenience =condition= can take a number of forms,
namely:
+ A regexp which is searched for in the export buffer.
+ A variable, if a string it is used as a regexp search, otherwise any
non-nil value is taken to imply =implied-features=.
+ A (unary) function, which is called with on the export communication
plist (~info~). A returned string is used as a regexp search,
otherwise any non-nil value is taken to imply =implied-features=.
As an example, a feature conditions alist which checks whether any
headings exist, and if the word "hello" appears could take the
following form:
#+begin_example
(((lambda (info)
(org-element-map (plist-get info :parse-tree) 'heading
#'identity info t))
headlines)
("hello" has-greeting))
#+end_example
Conditions are inherited from parent export backends and (for conditions general
enough to apply across backends) the variable ~org-export-conditional-features~.
#+begin_example
,--> beamer
/
html <----. ,----> latex --'
\ /
org-export-conditional-features
/ \
ascii <----' '----> odt
#+end_example
**** Feature implementations
The other half of the export feature system is of course producing
snippets of content from the list of features. Export backends can do
this at any point via ~org-export-expand-feature-snippets~. This
operates on a /feature implementation alist/. The implementation alist
is essentially a mirror of the condition alist, instead of =(condition
. feature-list)= elements it takes =(feature . implementation-plist)=
elements. This reversal of order may seem a bit odd, but it should
help make the condition--feature--implementation graph more apparent.
For example, considering this example condition alist and implementation alist
would be represented as the earlier graph.
#+begin_example
;; The condition alist
(([emoji predicate] emoji image)
([image predicate] image)
([inline LaTeX predicate] maths))
;; The implementation alist
((emoji [plist])
(image [plist])
(maths [plist])
#+end_example
The implementation plist recognises a number of keywords, but the
primary keyword is ~:snippet~. The snippet value provides the snippet
content used to provide the feature's capability. Much like
~condition~, it accepts a number of forms for convenience, namely:
+ A string, which is passed on.
+ A variable symbol, the value of which must be a string.
+ A (unary) function, which is called on the export communication
plist (~info~), and must return a string.
Note that no keys are mandatory in the implementation plist (not even
~:snippet~).
Like conditions, implementations are also inherited from parent backends, but
there is no "root" global list of implementations, as they are always
backend-specific.
#+begin_example
,--> beamer
/
html <---o o---> latex --'
ascii <---o o---> odt
#+end_example
**** Feature dependency and incompatibility
While just connecting features with snippets satisfies most use cases,
this system is designed to also allow for complex configurations of
inter-dependent snippets.
In slightly more complex examples, we may run across implementations
which either (a) only make sense when another feature is active, or
(b) require another implementation to be used in order to work. These
two situations are covered by the ~:when~ and ~:requires~ keywords
respectively. The accept either a single feature symbol or a list of
feature symbols.
For example, if an implementation contains ~:when featA~, it will only
be used when =featA= is active. If the implementation contains ~:when
(featA featB)~ it will require /both/ =featA= and =featB= to be
active. The ~:requires~ keyword works in the same way, but
unconditionally requires implementations instead of testing for them.
Occasionally one implementation may be incompatible with another. For
example, in LaTeX loading the same package with different options will
often produce an "options clash" error. To ensure that incompatible
implementations are not used, the ~:prevents~ keyword makes it as if
the feature were never used in the first place.
Circular ~:requires~ and ~:prevents~, or features that are
simultaneously required and prevented result in undefined behaviour.
Similarly, the behaviour of mutual ~:when~s (e.g. ~(a :when b) (b
:when a)~ is also undefined.
**** Feature ordering
In many scenarios it is not only /which/ snippets are included that
matters, but the /order/ in which they are placed. A requirement for a
certain snippet to appear before/after others can be specified through
the ~:before~ and ~:after~ keywords. Like ~:when~, ~:requires~, and
~:prevents~ they accept either a single feature symbol or a list of
feature symbols.
As an example, should an implementation plist contain ~:before featA
:after (featB featC)~ it will be placed after =featA= but before
=featB= and =featC=. It is possible to accidentally create circular
dependencies, in which case an error will be raised.
While ~:before~ and ~:after~ work well for specifying relative
ordering, it can also be useful to specify the /absolute/ ordering,
for instance to put something first or last. This can be controlled
via the ~:order~ keyword. Each implementation has an ~:order~ of zero
by default. Implementations with a higher ~:order~ come later.
# REVIEW maybe give a convention on :order ranges?
# Perhaps take inspiration from ~add-hook~.
-----
The overall ordering behaviour can be characterized as a ascending
sort of ~:order~ followed by a stable [[https://en.wikipedia.org/wiki/Topological_sorting][topological sort]] based on
~:before~ and ~:after~.
**** Adding or editing export features
The export features of a backend can be modified via the convenience
macro ~org-export-update-features~. This is invoked with the following
form:
#+begin_example
(org-export-update-features 'BACKEND
(FEATURE-NAME
:PROPERTY VALUE
...)
...)
#+end_example
For each feature mentioned, it sets the each =:PROPERTY= to =VALUE= in
the implementation plist. The one exception to this is ~:condition~ in
which case the backend's feature condition alist is modified so that
the condition is taken to imply the feature.
Setting ~:condition t~ will thus make the feature enabled by default. This is not
a special case, but rather an instance of the general behaviour of obtaining the
value of any non-function symbol provided, and as ~(symbol-value 't)~ is always
non-nil, the associated features will always be considered active. Conversely
setting ~:condition nil~ will make it so no conditions imply the feature. This is
possible thanks to special behavior that removes the feature from all other
conditions' associations when ~nil~ is given.
Since having a anonymous function (lambda) is expected to be
reasonably common with ~:condition~ and ~:snippet~, for those keywords
and sexp given is implicitly wrapped with ~(lambda (info) SEXP)~.
If the backend is not available at the time the feature update is run,
an error will be raised.
**** Custom export feature examples
To make the usage of ~org-export-update-features~ and the capabilities
of the export feature system clearer, here are a few examples
~org-export-update-features~ invocations.
Say you want to apply the [[https://ctan.org/pkg/chickenize][chickenize]] package to the word "wacky" when
the title starts with "wacky". We can implement that by testing for
the regexp =^#\\+title: Wacky= and including
src_latex{\usepackage[chickenstring[1]='wacky']{chickenize}} when it is
found.
#+begin_example
(org-export-update-features 'latex
(wacky-chicken
:condition "^#\\+title: Wacky"
:snippet "\\usepackage[chickenstring[1]='wacky']{chickenize}"))
#+end_example
However, if =#+title: Wacky= is placed inside an example block, this
regexp will match even though the match isn't actually parsed as a
keyword. To be more robust, we can inspect ~info~ instead.
#+begin_example
(org-export-update-features 'latex
(wacky-chicken
:condition (and (car (plist-get info :title))
(string-match-p "^Wacky" (car (plist-get info :title))))
:snippet "\\usepackage[chickenstring[1]='wacky']{chickenize}"))
#+end_example
=chickenize= is a LuaLaTeX only package, and so trying to use this
when compiling with pdfLaTeX or XeLaTeX will cause issues. This may
well apply to other snippets too, so it could make sense to make a
=lualatex= feature to indicate when LuaLaTeX is being used.
#+begin_example
(org-export-update-features 'latex
(lualatex
:condition (equal (plist-get info :latex-compiler) "lualatex")))
#+end_example
To only use the chickenize snippet with LuaLaTeX, we can now add
=lualatex= as a ~:when~ clause.
#+begin_example
(org-export-update-features 'latex
(wacky-chicken
:when lualatex))
#+end_example
Hopefully this has given you an impression of how ~:condition~, ~:when~, and
~:snippet~ can look in practice. To demonstrate ~:requires~, ~:prevents~, and
~:after~ we will consider another LaTeX example.
Say that you wanted a few named special blocks to automatically export nicely,
such as =#+begin_warning=, =#+begin_info=, and =#+begin_note=. All three of
these can be individually detected and handled appropriately. For the sake of
simplicity, a crude regexp will be used here, however examining the parse tree
would be a more robust solution.
#+begin_example
(org-export-update-features 'latex
(box-warning
:condition "^[ \t]*#\\+begin_warning"
:snippet "\\mysetupbox{warning}"
:requires mysetupbox
:after mysetupbox)
(box-info
:condition "^[ \t]*#\\+begin_info"
:snippet "\\mysetupbox{info}"
:requires mysetupbox
:after mysetupbox)
(box-note
:condition "^[ \t]*#\\+begin_note"
:snippet "\\mysetupbox{note}"
:requires mysetupbox
:after mysetupbox)
(mysetupbox
:snippet "\newcommand{\mysetupbox}...")
#+end_example
Here, all three box types make use of LaTeX command ~\mysetupbox~ which is
provided by the =mysetupbox= feature implementation. By using a ~:requires~ for
this, we can make sure it is availible that it is loaded once, and thanks to the
~:after mysetupbox~ lines the specific box setup invocations will occur after
the ~\newcommand{\mysetupbox}...~ definition.
Say that when using beamer you use a package that defines its own
warning/info/note environments and you'd like to use those. In that case one can
make an on-by-default beamer feature that prevents the box features from being
used.
#+begin_example
(org-export-update-features 'beamer
(no-custom-boxes
:condition t
:prevents (box-warning box-info box-note)))
#+end_example
**** Detailed explanation of the implementation resolution process
The previous descriptions of the "export feature" behaviour should give a clear
overview of how this feature works. In case more detail is wanted, or should
there be any ambiguity, here is a more technical description of the overall
feature implementation resolution process.
1. The list of detected features is used to obtain all applicable corresponding
feature implementations. Detected feature symbols may have /no/ corresponding
implementation.
2. The list of feature implementations is sorted according to ~:order~.
3. Using a queue, all required features (~:requires~) are added to the list of feature
implementations, as are their requirements recursively. Should a feature that
has no implementation be required, an ~org-missing-feature-dependency~ error is raised.
4. The implementations with a ~:when~ condition are scanned and marked as
confirmed when all of the ~:when~ conditions are known to be satisfied. This is
repeated until there is no change in the list of confirmed implementations,
at which point all non-confirmed implementations are removed.
5. For each of the feature implementations in turn, prevented features
(~:prevents~) are removed from the list. Feature implementations that are only
present because of a feature that has now been removed are themselves
removed, recursively.
6. The list of feature implementations is sorted according to ~:order~, again.
7. A stable topological sort is performed using ~:before~ and ~:after~. Should any
circular dependencies be found, a ~org-circular-feature-dependency~ error is raised.
** Export Region
:PROPERTIES:
:DESCRIPTION: Author tables and lists in Org syntax.
@ -22301,7 +22709,7 @@ Get all property keys in the current buffer.
#+attr_texinfo: :options org-insert-property-drawer
#+begin_defun
Insert a property drawer for the current entry. Also
Insert a property drawer for the current entry.
#+end_defun
#+attr_texinfo: :options org-entry-put-multivalued-property pom property &rest values
@ -22924,7 +23332,7 @@ modify this GNU manual."
#+export_file_name: org.texi
#+texinfo_dir_category: Emacs editing modes
#+texinfo_dir_title: Org Mode: (org)
#+texinfo_dir_name: Org Mode: (org)
#+texinfo_dir_desc: Outline-based notes management and organizer
* Footnotes
@ -23135,7 +23543,7 @@ used to create images, any LaTeX environment is handled.
[fn:38] These are respectively available at
[[https://sourceforge.net/projects/dvipng/]], [[http://dvisvgm.bplaced.net/]]
and from the ImageMagick suite. Choose the converter by setting the
variable ~org-preview-latex-default-process~ accordingly.
variable ~org-latex-preview-process-default~ accordingly.
[fn:39] This works automatically for the HTML backend (it requires
version 1.34 of the =htmlize.el= package, which you need to install).

View File

@ -13,6 +13,47 @@ Please send Org bug reports to mailto:emacs-orgmode@gnu.org.
* Version 9.7 (not released yet)
** Important announcements and breaking changes
*** ~org-latex-to-mathml-convert-command~ and ~org-latex-to-html-convert-command~ may need to be adjusted
Previously, =%i= placeholders in the
~org-latex-to-mathml-convert-command~ and
~org-latex-to-html-convert-command~ user options were replaced with
raw LaTeX fragment text, potentially triggering shell-expansion and
incorrect result.
Now, the =%i= placeholders are shell-escaped to prevent shell
expansion.
If you have single or double quotes around =%i= then update
customizations and remove quotes.
*** Org mode faces are now consistently combined, with markup faces taking precedence over the containing element faces
Previously, fontification of inline source blocks, macros, footnotes,
target links, timestamps, radio targets, targets, inline export
snippets, verbatim code, and COMMENT keyword in headings replaced the
containing element fontification. Now, this is changed - the inner
markup faces and the containing element faces are combined, with
"inner" faces taking precedence; just as for all other markup.
*** Built-in HTML, LaTeX, Man, Markdown, ODT, and Texinfo exporters preserve the link protocol during export
Previously, some link types where not exported as =protocol:uri= but
as bare =uri=. This is now changed.
When a link is known by Org mode and does not have a custom ~:export~
parameter (see A.3 Adding Hyperlink Types section of the manual), the
link protocol is now not stripped.
For example, if one adds a link type =tel=, but does not define
~:export~ parameter
: (org-link-set-parameters "tel")
=[[tel:12345][John Doe]]= link will be correctly exported to LaTeX as
=\href{tel:12345}{John Doe}=, not =\href{12345}{John Doe}=.
However, links like =[[elisp:(+ 1 2)]]= will be exported as
=\url{elisp:(+ 1 2)}=, which may be somewhat unexpected.
*** When ~org-link-file-path-type~ is a function, its argument is now a filename as it is read by ~org-insert-link~; not an absolute path
Previously, when ~org-link-file-path-type~ is set to a function, the
@ -468,9 +509,9 @@ indicating whether ~org-store-link~ was called interactively.
Existing store functions will continue to work.
*** ~org-priority=show~ command no longer adjusts for scheduled/deadline
*** ~org-priority-show~ command no longer adjusts for scheduled/deadline
In agenda views, ~org-priority=show~ command previously displayed the
In agenda views, ~org-priority-show~ command previously displayed the
composite rank consisting of the item priority and overdue. This is
no longer the case. The displayed and returned value only depends on
the item priority now.
@ -501,6 +542,157 @@ constant.
If you still want to use python-mode with ob-python, you might
consider [[https://gitlab.com/jackkamm/ob-python-mode-mode][ob-python-mode-mode]], where the code to support python-mode
has been ported to.
*** The LaTeX preview system has been overhauled
Org's LaTeX preview system has been overhauled
Org mode's LaTeX preview system has been rewritten with several improvements and new features.
- LaTeX Previews are generated in bulk, and hundreds of LaTeX fragments can be processed per second.
- Images are placed in the buffer continuously as they are generated.
- Preview generation is asynchronous and will not block Emacs.
- Inline previews are aligned and scaled to match the font baseline and size.
- Previews scale along with text when the text scale is changed.
- Previews are coloured to match surrounding text and the active theme.
- SVG previews automatically change colors when the active theme changes.
- Error encountered when compiling LaTeX fragments can be accessed by mousing over preview images.
- Preview overlays can hide and show themselves dynamically based on cursor position.
- Org mode can auto-generate LaTeX previews as you type or edit the text of existing ones.
- Org mode can keep equation numbering consistent by regenerating previews as needed.
**** New features
***** New minor mode ~org-latex-preview-auto-mode~
When this mode is turned on, LaTeX preview overlays in the buffer can be temporarily disabled by moving the cursor into them. Moving the cursor out will display the LaTeX preview image overlay again. Additionally, editing LaTeX fragments that have previews will cause the preview images to be updated.
If the option ~org-latex-preview-auto-track-inserts~ is non-nil (which see), previews for LaTeX fragments will be auto-generated as you type.
**** New options
***** A new option ~org-latex-preview-compiler-command-map~ for setting precompile commands
This alist maps compilers in ~org-latex-compilers~ to command strings
used for LaTeX precompilation when creating previews or LaTeX exports.
***** New option ~org-latex-preview-cache~ to enable preview image caching
When set to =persist=, images produced using ~org-latex-preview~ will
be cached and persisted across Emacs sessions using
~org-persist~. Temporary or custom directories can also be used.
***** New option ~org-latex-preview-persist-expiry~ to set persistence period
This is the number of days for which LaTeX preview images will be
cached, assuming persistence is turned on with
~org-latex-preview-cache~.
***** New option ~org-latex-preview-process-active-indicator~ to indicate preview processing for LaTeX fragments
This option controls the style of visual indicator for LaTeX fragments
currently being processed.
***** New option ~org-latex-preview-numbered~ to automatically renumber previewed LaTeX environments
When non-nil, previewed LaTeX environments in the buffer are
renumbered automatically as required.
***** New option =:page-width= in ~org-latex-preview-appearance-options~ to control the text width for LaTeX fragment previews
This option controls the width of text in preview images. This is
relevant for displaymath-type LaTeX environments, and can be specified
in multiple ways.
***** New option ~org-latex-preview-process-precompiled~ to control LaTeX precompilation
This option controls whether LaTeX headers for buffers are precompiled
when generating the first preview for the buffer. Precompilation can
speed up preview generation by a moderate to large amount depending on
the complexity of the header.
***** New option ~org-latex-preview-auto-track-inserts~ to auto-generate LaTeX previews when typing
When using ~org-latex-preview-auto-mode~ (which see), setting this option to a non-nil value will cause LaTeX previews to be rendered as you type LaTeX fragments. This works however new text is added to the buffer, for example by yanking. When this option is nil and ~org-latex-preview-auto-mode~ is on, existing previews for LaTeX fragments will still be auto-regenerated when edited but no new ones will be auto-generated.
**** Removed or renamed functions and variables
***** Mark ~org-format-latex-options~ obsolete
Use ~org-latex-preview-appearance-options~ instead. The replacement acts in the
same way, except that
- the preview image render size and display size can be independently
controlled with the =:scale= and =:zoom= plist keys, and
- the HTML export-specific parameters =:html-scale=,
=:html-foreground= and =:html-background= have been moved to
~org-html-latex-image-options~, which see.
- the new option =:page-width= (mentioned earlier)
***** Mark ~org-format-latex-header~ obsolete
Use ~org-latex-preview-header~ instead. The replacement variable
behaves the exact same way and is renamed for consistency.
***** Mark ~org-preview-latex-default-process~ obsolete
Use ~org-latex-preview-process-default~ instead. The replacement
variable behaves the exact same way and is renamed for consistency.
***** Mark ~org-preview-latex-process-alist~ obsolete
Use ~org-latex-preview-process-alist~ instead. The replacement
variable acts in the same way, except that =:latex-compiler= must now
be a single command or a list containing a single command. The
placeholder ="%S"= in the format string for =:latex-compiler= is
ignored.
***** Mark ~org-clear-latex-preview~ obsolete
Use ~org-latex-preview-clear-overlays~ instead. The replacement
function acts in the exact same way and is renamed for consistency.
***** Mark ~org-place-formula-image~ obsolete
This functionality is replaced with ~org-latex-preview-place-image~
(for images) and ~org-latex-preview-place-image-link~ (for links).
***** Mark ~org-latex-color-format~ obsolete
Use ~org-latex-preview--format-color~ instead. The replacement
function acts in the exact same way and is renamed for consistency.
***** Mark ~org-latex-color~ obsolete
Use ~org-latex-preview--attr-color~ instead. The replacement function
acts in the exact same way and is renamed for consistency.
***** Mark ~org-normalize-color~ obsolete
Use ~org-latex-preview--normalize-color~ instead. The replacement
function acts in the exact same way and is renamed for consistency.
***** Mark ~org-latex-to-mathml-jar-file~ obsolete
Use ~org-mathml-converter-jar-file~ instead. The replacement variable
acts in the exact same way and is renamed for consistency.
***** Mark ~org-latex-to-mathml-convert-command~ obsolete
Use ~org-mathml-convert-command~ instead. The replacement variable
acts in the exact same way and is renamed for consistency.
***** Mark ~org-format-latex-mathml-available-p~ obsolete
Use ~org-mathml-converter-available-p~ instead. The replacement
function acts in the exact same way and is renamed for consistency.
***** Mark ~org-create-math-formula~ obsolete
Use ~org-mathml-convert-latex~ instead. The replacement function acts
in the exact same way and is renamed for consistency.
*** =ox-icalendar.el= line ending fix may affect downstream packages
@ -569,6 +761,10 @@ link when storing any type of external link type in an Org file, not
just =id:= links.
** New and changed options
*** =.avif= images are not recognized in ~org-html-inline-image-rules~
In =ox-html=, =.avif= image links are now inlined by default.
*** New option ~org-beamer-frame-environment~
The new option defines name of an alternative environment to be used
@ -1103,6 +1299,13 @@ Maxima's graphics packages (~draw~ or ~plot~); the default remains
~plot~. The graphics terminal is now determined from the file-ending
of the file-name set in the ~:file~ header argument.
*** =ob-calc.el=: Support for tables in ~:var~
=ob-calc= now supports tables in ~:var~. They are converted to a
matrix or a vector depending on the dimensionality of the table. A
table with a single row is converted to a vector, the rest are
converted to a matrix.
*** Images and files in clipboard can be pasted
Org asks the user what must be done when pasting images and files
@ -1141,6 +1344,13 @@ anonymous footnotes automatically with ~org-footnote-new~.
The same can be done via startup options:
: #+STARTUP: fnanon
*** ox-texinfo always generates a ~@direntry~
We use defaults based on the file name and title of the document, and
place the entry in the ~Misc~ category if ~TEXINFO_DIR_CATEGORY~ is missing.
=TEXINFO_DIR_TITLE= is renamed to =TEXINFO_DIR_NAME=.
The old name is obsolete.
** New functions and changes in function arguments
*** New optional argument =UPDATE-HEADING= for ~org-bibtex-yank~

View File

@ -64,7 +64,19 @@
(var-names (mapcar #'symbol-name org--var-syms)))
(mapc
(lambda (pair)
(calc-push-list (list (cdr pair)))
(let ((val (cdr pair)))
(calc-push-list
;; For a vector, Calc follows the format (vec 1 2 3 ...) so
;; a matrix becomes (vec (vec 1 2 3) (vec 4 5 6) ...). See
;; the comments in "Arithmetic routines." section of
;; calc.el.
(list (if (listp val)
(cons 'vec
(if (null (cdr val))
(car val)
(mapcar (lambda (x) (if (listp x) (cons 'vec x) x))
val)))
val))))
(calc-store-into (car pair)))
vars)
(mapc

View File

@ -74,6 +74,31 @@ This is useful when prompt unexpectedly changes."
(setq comint-prompt-regexp org-babel-comint-prompt-regexp-old
org-babel-comint-prompt-regexp-old tmp))))
(defun org-babel-comint--prompt-filter (string &optional prompt-regexp)
"Remove PROMPT-REGEXP from STRING.
PROMPT-REGEXP defaults to `comint-prompt-regexp'."
(let* ((prompt-regexp (or prompt-regexp comint-prompt-regexp))
;; We need newline in case if we do progressive replacement
;; of agglomerated comint prompts with `comint-prompt-regexp'
;; containing ^.
(separator "org-babel-comint--prompt-filter-separator\n"))
(while (string-match-p prompt-regexp string)
(setq string
(replace-regexp-in-string
(format "\\(?:%s\\)?\\(?:%s\\)[ \t]*" separator prompt-regexp)
separator string)))
(delete "" (split-string string separator))))
(defun org-babel-comint--echo-filter (string &optional echo)
"Remove ECHO from STRING."
(and echo string
(string-match
(replace-regexp-in-string "\n" "[\r\n]+" (regexp-quote echo))
string)
(setq string (substring string (match-end 0))))
string)
(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
@ -90,12 +115,7 @@ or user `keyboard-quit' during execution of body."
(let ((buffer (nth 0 meta))
(eoe-indicator (nth 1 meta))
(remove-echo (nth 2 meta))
(full-body (nth 3 meta))
(org-babel-comint-prompt-separator
;; We need newline in case if we do progressive replacement
;; of agglomerated comint prompts with `comint-prompt-regexp'
;; containing ^.
"org-babel-comint-prompt-separator\n"))
(full-body (nth 3 meta)))
`(org-babel-comint-in-buffer ,buffer
(let* ((string-buffer "")
(comint-output-filter-functions
@ -139,31 +159,12 @@ or user `keyboard-quit' during execution of body."
(goto-char (process-mark (get-buffer-process (current-buffer))))
(insert dangling-text)
;; remove echo'd FULL-BODY from input
(and ,remove-echo ,full-body
(setq string-buffer (org-babel-comint--echo-filter string-buffer ,full-body)))
;; Filter out prompts.
(while (string-match-p comint-prompt-regexp string-buffer)
(setq string-buffer
(replace-regexp-in-string
;; Sometimes, we get multiple agglomerated
;; prompts together in a single output:
;; "prompt prompt prompt output"
;; Or even "<whitespace>prompt<whitespace>prompt ...>.
;; Remove them progressively, so that
;; possible "^" in the prompt regexp gets to
;; work as we remove the heading prompt
;; instance.
(format "\\(?:%s\\)?\\(?:%s\\)[ \t]*" ,org-babel-comint-prompt-separator comint-prompt-regexp)
,org-babel-comint-prompt-separator
string-buffer)))
;; 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))))
(delete "" (split-string
string-buffer
,org-babel-comint-prompt-separator))))))
(org-babel-comint--prompt-filter string-buffer)))))
(defun org-babel-comint-input-command (buffer cmd)
"Pass CMD to BUFFER.
@ -324,9 +325,10 @@ STRING contains the output originally inserted into the comint buffer."
until (and (equal (match-string 1) "start")
(equal (match-string 2) uuid))
finally return (+ 1 (match-end 0)))))
;; Apply callback to clean up the result
(res-str (funcall org-babel-comint-async-chunk-callback
res-str-raw)))
;; Remove prompt
(res-promptless (org-trim (string-join (mapcar #'org-trim (org-babel-comint--prompt-filter res-str-raw)) "\n") "\n"))
;; Apply user callback
(res-str (funcall org-babel-comint-async-chunk-callback res-promptless)))
;; Search for uuid in associated org-buffers to insert results
(cl-loop for buf in org-buffers
until (with-current-buffer buf

View File

@ -218,22 +218,27 @@ this template."
(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 source block
;; but preserve following white spaces.
;; Then insert value.
(unless (string= replacement
(buffer-substring begin end))
(delete-region begin end)
(insert replacement))))))
(cond
((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))))
((not replacement)
;; Replacement code cannot be determined.
;; Leave the code block as is.
(goto-char end))
;; Otherwise: remove inline source block
;; but preserve following white spaces.
;; Then insert value.
((not (string= replacement
(buffer-substring begin end)))
(delete-region begin end)
(insert replacement))))))
((or `babel-call `inline-babel-call)
(org-babel-exp-do-export
(or (org-babel-lob-get-info element)
@ -249,21 +254,27 @@ this template."
;; 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))))
(cond
((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)))))
((not rep)
;; Replacement code cannot be determined.
;; Leave the code block as is.
(goto-char end))
(t
;; Otherwise, preserve trailing
;; spaces/newlines and then, insert
;; replacement string.
(goto-char begin)
(delete-region begin end)
(insert rep))))
(insert rep)))))
(`src-block
(let ((match-start (copy-marker (match-beginning 0)))
(ind (org-current-text-indentation)))
@ -335,6 +346,8 @@ this template."
TYPE is the code block type: `block', `inline', or `lob'. HASH is the
result hash.
Return nil when exported content cannot be determined.
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)
@ -348,7 +361,10 @@ The function respects the value of the :exports header argument."
("results" (org-babel-exp-results info type nil hash) "")
("both"
(org-babel-exp-results info type nil hash)
(org-babel-exp-code info type)))))
(org-babel-exp-code info type))
(unknown-value
(warn "Unknown value of src block parameter :exports %S" unknown-value)
nil))))
(defcustom org-babel-exp-code-template
"#+begin_src %lang%switches%flags\n%body\n#+end_src"

View File

@ -37,7 +37,7 @@
(require 'ob)
(require 'org-macs)
(declare-function org-create-formula-image "org" (string tofile options buffer &optional type))
(declare-function org-latex-preview-create-image "org-latex-preview" (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))
@ -48,10 +48,10 @@
(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-latex-preview-header) ; From org-latex-preview.el
(defvar org-latex-preview-appearance-options) ; From org-latex-preview.el
(defvar org-latex-default-packages-alist) ; From org-latex-preview.el
(defvar org-latex-packages-alist) ; From org-latex-preview.el
(defvar org-babel-default-header-args:latex
'((:results . "latex") (:exports . "results"))
@ -167,11 +167,11 @@ This function is called by `org-babel-execute-src-block'."
(append (cdr (assq :packages params)) org-latex-packages-alist)))
(cond
((and (string-suffix-p ".png" out-file) (not imagemagick))
(let ((org-format-latex-header
(concat org-format-latex-header "\n"
(let ((org-latex-preview-header
(concat org-latex-preview-header "\n"
(mapconcat #'identity headers "\n"))))
(org-create-formula-image
body out-file org-format-latex-options in-buffer)))
(org-latex-preview-create-image
body out-file org-latex-preview-appearance-options in-buffer)))
((string= "svg" extension)
(with-temp-file tex-file
(insert (concat (funcall org-babel-latex-preamble params)
@ -238,7 +238,7 @@ This function is called by `org-babel-execute-src-block'."
(insert
(org-latex-guess-inputenc
(org-splice-latex-header
org-format-latex-header
org-latex-preview-header
(delq
nil
(mapcar

View File

@ -81,7 +81,8 @@ is modified outside the Customize interface."
(lambda (body params)
(:documentation
(format "Execute a block of %s commands with Babel." name))
(let ((shell-file-name name))
(let ((explicit-shell-file-name name)
(shell-file-name name))
(org-babel-execute:shell body params))))
(put fname 'definition-name 'org-babel-shell-initialize))
(defalias (intern (concat "org-babel-variable-assignments:" name))

View File

@ -222,14 +222,10 @@ source code blocks by languages matching a regular expression.
Return list of the tangled file names."
(interactive "fFile to tangle: \nP")
(let* ((visited (find-buffer-visiting file))
(buffer (or visited (find-file-noselect file))))
(prog1
(with-current-buffer buffer
(org-with-wide-buffer
(mapcar #'expand-file-name
(org-babel-tangle nil target-file lang-re))))
(unless visited (kill-buffer buffer)))))
(org-with-file-buffer file
(org-with-wide-buffer
(mapcar #'expand-file-name
(org-babel-tangle nil target-file lang-re)))))
(defun org-babel-tangle-publish (_ filename pub-dir)
"Tangle FILENAME and place the results in PUB-DIR."

View File

@ -78,6 +78,9 @@
(declare-function org-open-at-point "org" (&optional arg))
(declare-function org-open-file "org" (path &optional in-emacs line search))
(declare-function org-element-create "org-element-ast" (type &optional props &rest children))
(declare-function org-element-set "org-element-ast" (old new &optional keep-props))
(declare-function org-element-interpret-data "org-element" (data))
(declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
(declare-function org-element-map "org-element"

View File

@ -376,61 +376,47 @@ INFO is the export state, as a property list."
(other
(user-error "Invalid entry %S in `org-cite-biblatex-styles'" other))))))
(defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
"Prepare document preamble for \"biblatex\" usage.
(defun org-cite-biblatex--generate-latex-usepackage (info)
"Ensure that the biblatex package is loaded.
This is performed by extracting relevant information from the
INFO export plist, and modifying any existing
\\usepackage{biblatex} statement in the LaTeX header."
(let ((style (org-cite-bibliography-style info))
(usepackage-rx (rx "\\usepackage"
(opt (group "[" (*? anything) "]"))
"{biblatex}")))
(concat
(if (string-match usepackage-rx (plist-get info :latex-full-header))
;; "biblatex" package loaded, but with none (or different) options.
;; Replace with style-including command.
(plist-put info :latex-full-header
(replace-match
(format "\\usepackage%s{biblatex}"
(save-match-data
(org-cite-biblatex--package-options nil style)))
t t
(plist-get info :latex-full-header)))
;; No "biblatex" package loaded. Insert "usepackage" command
;; with appropriate options, including style.
(format "\\usepackage%s{biblatex}\n"
(org-cite-biblatex--package-options
org-cite-biblatex-options style))))))
OUTPUT is the final output of the export process. FILES is the list of file
names used as the bibliography.
This function ensures \"biblatex\" package is required. It also adds resources
to the document, and set styles."
(with-temp-buffer
(save-excursion (insert output))
(when (search-forward "\\begin{document}" nil t)
;; Ensure there is a \usepackage{biblatex} somewhere or add one.
;; Then set options.
(goto-char (match-beginning 0))
(let ((re (rx "\\usepackage"
(opt (group "[" (*? anything) "]"))
"{biblatex}")))
(cond
;; No "biblatex" package loaded. Insert "usepackage" command
;; with appropriate options, including style.
((not (re-search-backward re nil t))
(save-excursion
(insert
(format "\\usepackage%s{biblatex}\n"
(org-cite-biblatex--package-options
org-cite-biblatex-options style)))))
;; "biblatex" package loaded, but without any option.
;; Include style only.
((not (match-beginning 1))
(search-forward "{" nil t)
(insert (org-cite-biblatex--package-options nil style)))
;; "biblatex" package loaded with some options set. Override
;; style-related options with ours.
(t
(replace-match
(save-match-data
(org-cite-biblatex--package-options (match-string 1) style))
nil nil nil 1))))
;; Insert resources below.
(forward-line)
(insert (mapconcat (lambda (f)
(format "\\addbibresource%s{%s}"
(if (org-url-p f) "[location=remote]" "")
f))
files
"\n")
"\n"))
(buffer-string)))
(defun org-cite-biblatex--generate-latex-bibresources (info)
"From INFO generate LaTeX that loads the relevant bibliography resource files."
(let ((files (plist-get info :bibliography)))
(mapconcat (lambda (f)
(format "\\addbibresource%s{%s}"
(if (org-url-p f) "[location=remote]" "")
f))
files
"\n")))
;;; Register `biblatex' processor
(org-cite-register-processor 'biblatex
:export-bibliography #'org-cite-biblatex-export-bibliography
:export-citation #'org-cite-biblatex-export-citation
:export-finalizer #'org-cite-biblatex-prepare-preamble
:cite-styles #'org-cite-biblatex-list-styles)
(provide 'oc-biblatex)

View File

@ -847,27 +847,11 @@ INFO is the export state, as a property list."
;; process.
(org-cite-parse-elements output)))))
(defun org-cite-csl-finalizer (output _keys _files _style _backend info)
"Add \"hanging\" package if missing from LaTeX output.
OUTPUT is the export document, as a string. INFO is the export state, as a
property list."
(org-cite-csl--barf-without-citeproc)
(if (not (eq 'org-latex (org-cite-csl--output-format info)))
output
(with-temp-buffer
(save-excursion (insert output))
(when (search-forward "\\begin{document}" nil t)
(goto-char (match-beginning 0))
;; Insert the CSL-specific parts of the LaTeX preamble.
(insert (org-cite-csl--generate-latex-preamble info)))
(buffer-string))))
;;; Register `csl' processor
(org-cite-register-processor 'csl
:export-citation #'org-cite-csl-render-citation
:export-bibliography #'org-cite-csl-render-bibliography
:export-finalizer #'org-cite-csl-finalizer
:cite-styles
'((("author" "a") ("bare" "b") ("caps" "c") ("full" "f") ("bare-caps" "bc") ("caps-full" "cf") ("bare-caps-full" "bcf"))
(("noauthor" "na") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))

View File

@ -168,32 +168,25 @@ state, as a property list."
(org-cite-natbib--build-optional-arguments citation info)
(org-cite-natbib--build-arguments citation)))
(defun org-cite-natbib-use-package (output &rest _)
"Ensure output requires \"natbib\" package.
OUTPUT is the final output of the export process."
(with-temp-buffer
(save-excursion (insert output))
(when (search-forward "\\begin{document}" nil t)
;; Ensure there is a \usepackage{natbib} somewhere or add one.
(goto-char (match-beginning 0))
(let ((re (rx "\\usepackage" (opt "[" (*? nonl) "]") "{natbib}")))
(unless (re-search-backward re nil t)
(insert
(format "\\usepackage%s{natbib}\n"
(if (null org-cite-natbib-options)
""
(format "[%s]"
(mapconcat #'symbol-name
org-cite-natbib-options
","))))))))
(buffer-string)))
(defun org-cite-natbib--generate-latex-preamble (info)
"Ensure that the \"natbib\" package is loaded.
INFO is a plist used as a communication channel."
(and (not (string-match
(rx "\\usepackage" (opt "[" (*? nonl) "]") "{natbib}")
(plist-get info :latex-full-header)))
(format "\\usepackage%s{natbib}\n"
(if (null org-cite-natbib-options)
""
(format "[%s]"
(mapconcat #'symbol-name
org-cite-natbib-options
","))))))
;;; Register `natbib' processor
(org-cite-register-processor 'natbib
:export-bibliography #'org-cite-natbib-export-bibliography
:export-citation #'org-cite-natbib-export-citation
:export-finalizer #'org-cite-natbib-use-package
:cite-styles
'((("author" "a") ("caps" "a") ("full" "f"))
(("noauthor" "na") ("bare" "b"))

View File

@ -923,6 +923,13 @@ PARAMETERS should be keyword value pairs. See
(org-link-make-regexps)
(when (featurep 'org-element) (org-element-update-syntax)))))
;; This way, one can add multiple functions as, say, :follow parameter.
;; For example,
;; (add-function :before-until (org-link-get-parameter "id" :follow) #'my-function)
;; See https://orgmode.org/list/a123389c-8f86-4836-a4fe-1e3f4281d33b@app.fastmail.com
(gv-define-setter org-link-get-parameter (value type key)
`(org-link-set-parameters ,type ,key ,value))
(defun org-link-make-regexps ()
"Update the link regular expressions.
This should be called after the variable `org-link-parameters' has changed."
@ -1149,6 +1156,9 @@ and then used in capture templates."
if store-func
collect store-func))
(defvar org-link--abbrev-functions nil
"Alist of abbrev link expressions and functions.")
(defun org-link-expand-abbrev (link)
"Replace link abbreviations in LINK string.
Abbreviations are defined in `org-link-abbrev-alist'."
@ -1163,14 +1173,27 @@ Abbreviations are defined in `org-link-abbrev-alist'."
(setq rpl (cdr as))
(cond
((symbolp rpl) (funcall rpl tag))
((string-match "%(\\([^)]+\\))" rpl)
((string-match "%(\\([^) ]+\\))" rpl) ; %(function)
(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))
((string-match "%(\\(.+\\))" rpl) ; %(sexpr using tag)
(replace-match
(save-match-data
(funcall (or (cdr (assoc (match-string 1 rpl)
org-link--abbrev-functions))
(cdar (push (cons (match-string 1 rpl)
(eval (read (format
"(lambda (tag) (%s))"
(match-string 1 rpl)))))
org-link--abbrev-functions)))
tag))
t t rpl))
((string-match-p "%[0-<>^_]?[0-9]*\\(?:\\.[0-9]+\\)?s" rpl)
(format-spec rpl `((?s . ,(or tag "")))))
((string-match-p "%[0-<>^_]?[0-9]*\\(?:\\.[0-9]+\\)?h" rpl)
(format-spec rpl `((?h . ,(url-hexify-string (or tag ""))))))
(t (concat rpl tag)))))))
(defun org-link-open (link &optional arg)

View File

@ -8194,10 +8194,12 @@ which see."
(confirm (lambda (x) (stringp x)))
(prefix "")
(operator "")
table)
table
begin)
(when (string-match "^\\(.*\\([-+<>=]\\)\\)\\([^-+<>=]*\\)$" string)
(setq prefix (match-string 1 string)
operator (match-string 2 string)
begin (match-beginning 3)
string (match-string 3 string)))
(cond
((member operator '("+" "-" "" nil))
@ -8214,6 +8216,11 @@ which see."
(pcase flag
(`t (all-completions string table confirm))
(`lambda (assoc string table)) ;exact match?
(`(boundaries . ,suffix)
(let ((end (if (string-match "[-+<>=]" suffix)
(match-string 0 suffix)
(length suffix))))
`(boundaries ,(or begin 0) . ,end)))
(`nil
(pcase (try-completion string table confirm)
((and completion (pred stringp))
@ -10276,7 +10283,8 @@ ARG is passed through to `org-deadline'."
(unless (marker-buffer org-clock-marker)
(user-error "No running clock"))
(org-with-remote-undo (marker-buffer org-clock-marker)
(org-clock-cancel)))
(org-clock-cancel))
(org-agenda-unmark-clocking-task))
(defun org-agenda-clock-goto ()
"Jump to the currently clocked in task within the agenda.

View File

@ -254,8 +254,7 @@ direct children of this heading."
(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))
((find-file-noselect afile 'nowarn))
(t (error "Cannot access file \"%s\"" afile))))
(org-odd-levels-only
(if (local-variable-p 'org-odd-levels-only (current-buffer))

View File

@ -371,6 +371,10 @@ be replaced with content and expanded:
%^{prompt} Prompt the user for a string and replace this sequence with it.
A default value and a completion table can be specified like this:
%^{prompt|default|completion2|completion3|...}.
%^{prompt}X where X is one of g, G, t, T, u, U, C, or L.
Same as %^X (see above), but also supply custom
prompt/completions. Default value and completions as in
%^{prompt|default|...}X are allowed.
%? 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.

View File

@ -232,6 +232,18 @@ removed."
default)))
": ")))
(if (fboundp 'ensure-list)
(defalias 'org-ensure-list #'ensure-list)
(defun org-ensure-list (object)
"Return OBJECT as a list.
If OBJECT is already a list, return OBJECT itself. If it's
not a list, return a one-element list containing OBJECT.
Compatability substitute for `ensure-list' in Emacs 28."
(if (listp object)
object
(list object))))
;;; Emacs < 27.1 compatibility
@ -655,6 +667,393 @@ This constant, for example, makes the below code not err:
"use `org-element' library"
"9.0")
(define-obsolete-variable-alias
'org-format-latex-options 'org-latex-preview-appearance-options "9.7")
(make-obsolete-variable
'org-format-latex-signal-error "no longer used" "9.7")
(define-obsolete-variable-alias
'org-format-latex-header 'org-latex-preview-preamble "9.7")
(define-obsolete-variable-alias
'org-preview-latex-default-process 'org-latex-preview-process-default "9.7")
(define-obsolete-variable-alias
'org-preview-latex-process-alist 'org-latex-preview-process-alist "9.7")
(define-obsolete-function-alias
'org-clear-latex-preview 'org-latex-preview-clear-overlays "9.7")
(make-obsolete
'org-place-formula-image "no longer used" "9.7")
(define-obsolete-function-alias
'org-latex-color-format 'org-latex-preview--format-color "9.7")
(define-obsolete-function-alias
'org-latex-color 'org-latex-preview--attr-color "9.7")
;; MathML related functions from org-latex-preview.el
(define-obsolete-variable-alias
'org-latex-to-mathml-jar-file 'org-mathml-converter-jar-file "9.7")
(define-obsolete-variable-alias
'org-latex-to-mathml-convert-command 'org-mathml-convert-command "9.7")
(define-obsolete-function-alias
'org-format-latex-mathml-available-p 'org-mathml-converter-available-p "9.7")
(define-obsolete-function-alias
'org-create-math-formula 'org-mathml-convert-latex "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(defun org-format-latex-as-mathml (latex-frag latex-frag-type
prefix &optional dir)
(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-mathml-convert-latex 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)))
(make-obsolete #'org-format-latex-as-mathml "to be removed" "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(defun org-dvipng-color (attr)
"Return a RGB color specification for dvipng."
(org-dvipng-color-format (face-attribute 'default attr nil)))
;; FIXME: Unused; obsoleted; to be removed.
(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-latex-preview--normalize-color
(color-values color-name))))
(make-obsolete
'org-dvipng-color "to be removed" "9.7")
(make-obsolete
'org-dvipng-color-format "to be removed" "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(defun org-normalize-color (value)
"Return string to be used as color value for an RGB component."
(format "%g" (/ value 65535.0)))
(make-obsolete 'org-normalize-color "to be removed" "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(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)
(make-obsolete-variable
'org-preview-latex-image-directory "replaced with org-persist" "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(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) "\\)"))))
((eq processing-type 'html)
(goto-char beg)
(delete-region beg end)
(insert (org-format-latex-as-html value)))
((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 forbuffer
(cond
((eq color 'auto)
(face-attribute face :foreground nil 'default))
((eq color 'default)
(face-attribute 'default :foreground nil))
(t color))
color)))
(bg
(let ((color (plist-get org-format-latex-options
:background)))
(if forbuffer
(cond
((eq color 'auto)
(face-attribute face :background nil 'default))
((eq color 'default)
(face-attribute 'default :background nil))
(t color))
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))
(org-place-formula-image link block-type beg end value overlays movefile imagetype)))
((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)))))))))))
;; FIXME: Unused; obsoleted; to be removed.
(defun org-place-formula-image (link block-type beg end value overlays movefile imagetype)
"Place an overlay from BEG to END showing MOVEFILE.
The overlay will be above BEG if OVERLAYS is non-nil."
(if overlays
(progn
(dolist (o (overlays-in beg end))
(when (eq (overlay-get o 'org-overlay-type)
'org-latex-overlay)
(delete-overlay o)))
(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 movefile :ascent 'center)))
(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))))))
;; FIXME: Unused; obsoleted; to be removed.
(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) ""))
(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))
(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 (and buffer (display-graphic-p)) (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"))
(image-converter
(or (and (string= bg "Transparent")
(plist-get processing-info :transparent-image-converter))
(plist-get processing-info :image-converter)))
(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 (eq fg 'default)
(setq fg (org-latex-color :foreground))
(setq fg (org-latex-color-format fg)))
(setq bg (cond
((eq bg 'default) (org-latex-color :background))
((string= bg "Transparent") nil)
(t (org-latex-color-format bg))))
;; Remove TeX \par at end of snippet to avoid trailing space.
(if (string-suffix-p string "\n")
(aset string (1- (length string)) ?%)
(setq string (concat string "%")))
(with-temp-file texfile
(insert latex-header)
(insert "\n\\begin{document}\n"
"\\definecolor{fg}{rgb}{" fg "}%\n"
(if bg
(concat "\\definecolor{bg}{rgb}{" bg "}%\n"
"\n\\pagecolor{bg}%\n")
"")
"\n{\\color{fg}\n"
string
"\n}\n"
"\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
`((?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)))
;; FIXME: Unused; obsoleted; to be removed.
(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', `html', 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 (or (eq processing-type 'mathjax)
(eq processing-type 'html))
(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))))
(org-export-with-buffer-copy
:to-buffer (get-buffer-create " *Org HTML Export LaTeX*")
:drop-visibility t :drop-narrowing t :drop-contents t
(erase-buffer)
(insert latex-frag)
(org-format-latex cache-relpath nil nil cache-dir nil
"Creating LaTeX Image..." nil processing-type)
(buffer-string))))
(make-obsolete #'org-format-latex "to be removed" "9.7")
(make-obsolete #'org-create-formula-image "to be removed" "9.7")
(make-obsolete #'org-html-format-latex "to be removed" "9.7")
;; FIXME: Unused; obsoleted; to be removed.
(defun org-let (list &rest body) ;FIXME: So many kittens are suffering here.
(declare (indent 1) (obsolete cl-progv "2021"))

View File

@ -2291,9 +2291,8 @@ Return a new syntax node of `clock' type containing `:status',
`:value', `:time', `:begin', `:end', `:post-blank' and
`:post-affiliated' as properties."
(save-excursion
(let* ((case-fold-search nil)
(begin (point))
(value (progn (search-forward "CLOCK:" (line-end-position) t)
(let* ((begin (point))
(value (progn (search-forward "CLOCK:" (line-end-position))
(skip-chars-forward " \t")
(org-element-timestamp-parser)))
(duration (and (search-forward " => " (line-end-position) t)
@ -5929,6 +5928,7 @@ FORMAT-STRING and ARGS are the same arguments as in `format'."
(setq org-element--cache-diagnostics-ring nil)))))
(if (and (boundp 'org-batch-test) org-batch-test)
(error "%s" (concat "org-element--cache: " format-string))
(push (concat "org-element--cache: " format-string) org--warnings)
(display-warning '(org-element org-element-cache)
(concat "org-element--cache: " format-string)))))

View File

@ -554,7 +554,10 @@ and the setup appears to be created for different buffer,
copy the old invisibility state into new buffer-local text properties,
unless RETURN-ONLY is non-nil."
(if (eq org-fold-core-style 'overlays)
(org-fold-core-get-folding-property-symbol spec nil 'global)
(or (gethash (cons 'global spec) org-fold-core--property-symbol-cache)
(puthash (cons 'global spec)
(org-fold-core-get-folding-property-symbol spec nil 'global)
org-fold-core--property-symbol-cache))
(let* ((buf (or buffer (current-buffer))))
;; Create unique property symbol for SPEC in BUFFER
(let ((local-prop (or (gethash (cons buf spec) org-fold-core--property-symbol-cache)
@ -1068,8 +1071,9 @@ If SPEC-OR-ALIAS is omitted and FLAG is nil, unfold everything in the region."
(when org-fold-core--isearch-active
(cl-pushnew ov org-fold-core--isearch-overlays)))))
(overlays-in from to))
(remove-overlays from to 'org-invisible spec)
(remove-overlays from to 'invisible spec)))
(when spec
(remove-overlays from to 'org-invisible spec)
(remove-overlays from to 'invisible spec))))
(if flag
(if (not spec)
(error "Calling `org-fold-core-region' with missing SPEC")

View File

@ -90,6 +90,21 @@
(declare-function org-end-of-line "org" (&optional n))
(declare-function org-entry-put "org" (pom property value))
(declare-function org-eval-in-calendar "org" (form &optional keepdate))
(declare-function org-calendar-goto-today-or-insert-dot "org" ())
(declare-function org-calendar-goto-today "org" ())
(declare-function org-calendar-backward-month "org" ())
(declare-function org-calendar-forward-month "org" ())
(declare-function org-calendar-backward-year "org" ())
(declare-function org-calendar-forward-year "org" ())
(declare-function org-calendar-backward-week "org" ())
(declare-function org-calendar-forward-week "org" ())
(declare-function org-calendar-backward-day "org" ())
(declare-function org-calendar-forward-day "org" ())
(declare-function org-calendar-view-entries "org" ())
(declare-function org-calendar-scroll-month-left "org" ())
(declare-function org-calendar-scroll-month-right "org" ())
(declare-function org-calendar-scroll-three-months-left "org" ())
(declare-function org-calendar-scroll-three-months-right "org" ())
(declare-function org-evaluate-time-range "org" (&optional to-buffer))
(declare-function org-export-dispatch "org" (&optional arg))
(declare-function org-feed-goto-inbox "org" (feed))
@ -349,71 +364,25 @@ COMMANDS is a list of alternating OLDDEF NEWDEF command names."
(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 (kbd "M-S-<left>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-month 1))))
(org-defkey map (kbd "ESC S-<left>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-month 1))))
(org-defkey map (kbd "M-S-<right>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-month 1))))
(org-defkey map (kbd "ESC S-<right>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-month 1))))
(org-defkey map (kbd "M-S-<up>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-year 1))))
(org-defkey map (kbd "ESC S-<up>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-year 1))))
(org-defkey map (kbd "M-S-<down>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-year 1))))
(org-defkey map (kbd "ESC S-<down>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-year 1))))
(org-defkey map (kbd "S-<up>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-week 1))))
(org-defkey map (kbd "S-<down>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-week 1))))
(org-defkey map (kbd "S-<left>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-backward-day 1))))
(org-defkey map (kbd "S-<right>")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-forward-day 1))))
(org-defkey map (kbd "!")
(lambda () (interactive)
(org-eval-in-calendar '(diary-view-entries))
(message "")))
(org-defkey map (kbd ">")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-scroll-left 1))))
(org-defkey map (kbd "<")
(lambda () (interactive)
(org-eval-in-calendar '(calendar-scroll-right 1))))
(org-defkey map (kbd "C-v")
(lambda () (interactive)
(org-eval-in-calendar
'(calendar-scroll-left-three-months 1))))
(org-defkey map (kbd "M-v")
(lambda () (interactive)
(org-eval-in-calendar
'(calendar-scroll-right-three-months 1))))
(org-defkey map (kbd ".") #'org-calendar-goto-today-or-insert-dot)
(org-defkey map (kbd "C-.") #'org-calendar-goto-today)
(org-defkey map (kbd "M-S-<left>") #'org-calendar-backward-month)
(org-defkey map (kbd "ESC S-<left>") #'org-calendar-backward-month)
(org-defkey map (kbd "M-S-<right>") #'org-calendar-forward-month)
(org-defkey map (kbd "ESC S-<right>") #'org-calendar-forward-month)
(org-defkey map (kbd "M-S-<up>") #'org-calendar-backward-year)
(org-defkey map (kbd "ESC S-<up>") #'org-calendar-backward-year)
(org-defkey map (kbd "M-S-<down>") #'org-calendar-forward-year)
(org-defkey map (kbd "ESC S-<down>") #'org-calendar-forward-year)
(org-defkey map (kbd "S-<up>") #'org-calendar-backward-week)
(org-defkey map (kbd "S-<down>") #'org-calendar-forward-week)
(org-defkey map (kbd "S-<left>") #'org-calendar-backward-day)
(org-defkey map (kbd "S-<right>") #'org-calendar-forward-day)
(org-defkey map (kbd "!") #'org-calendar-view-entries)
(org-defkey map (kbd ">") #'org-calendar-scroll-month-left)
(org-defkey map (kbd "<") #'org-calendar-scroll-month-right)
(org-defkey map (kbd "C-v") #'org-calendar-scroll-three-months-left)
(org-defkey map (kbd "M-v") #'org-calendar-scroll-three-months-right)
map)
"Keymap for minibuffer commands when using `org-read-date'.")

2986
lisp/org-latex-preview.el Normal file

File diff suppressed because it is too large Load Diff

View File

@ -112,6 +112,13 @@ previous one, unless VALUE is nil. Return the updated list."
(let ((new-templates nil))
(pcase-dolist (`(,name . ,value) templates)
(let ((old-definition (assoc name new-templates)))
;; This code can be evaluated unconditionally, as a part of
;; loading Org mode. We *must not* evaluate any code present
;; inside the Org buffer while loading. Org buffers may come
;; from various sources, like received email messages from
;; potentially malicious senders. Org mode might be used to
;; preview such messages and no code evaluation from inside the
;; received Org text should ever happen without user consent.
(when (and (stringp value) (string-match-p "\\`(eval\\>" value))
;; Pre-process the evaluation form for faster macro expansion.
(let* ((args (org-macro--makeargs value))
@ -124,7 +131,7 @@ previous one, unless VALUE is nil. Return the updated list."
(cadr (read value))
(error
(user-error "Invalid definition for macro %S" name)))))
(setq value (eval (macroexpand-all `(lambda ,args ,body)) t))))
(setq value `(lambda ,args ,body))))
(cond ((and value old-definition) (setcdr old-definition value))
(old-definition)
(t (push (cons name (or value "")) new-templates)))))

View File

@ -291,6 +291,31 @@ FILE is the file name passed to `find-buffer-visiting'."
(find-buffer-visiting file))))
(org-base-buffer buf)))
(defvar-local org-file-buffer-created nil
"Non-nil when current buffer is created from `org-with-file-buffer'.
The value is FILE argument passed to `org-with-file-buffer'.")
(defmacro org-with-file-buffer (file &rest body)
"Evaluate BODY with current buffer visiting FILE.
When no live buffer is visiting FILE, create one and kill after
evaluating BODY.
During evaluation, when the buffer was created, `org-file-buffer-created'
variable is set to FILE."
(declare (debug (form body)) (indent 1))
(org-with-gensyms (mark-function filename buffer)
`(let ((,mark-function (lambda () (setq-local org-file-buffer-created ,file)))
(,filename ,file)
,buffer)
(add-hook 'find-file-hook ,mark-function)
(unwind-protect
(progn
(setq ,buffer (find-file-noselect ,filename t))
(with-current-buffer ,buffer
(prog1 (progn ,@body)
(with-current-buffer ,buffer
(when (equal ,filename org-file-buffer-created)
(kill-buffer))))))
(remove-hook 'find-file-hook ,mark-function)))))
(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.
@ -344,6 +369,278 @@ If EXCLUDE-TMP is non-nil, ignore temporary buffers."
nil))
(buffer-list)))))
;;; Async stack
(defvar org-async--stack nil
"List of async currently running task forms.
Each running task is represented by a list with the following structure:
(%PROCESS :success %FUN :failure %FUN
:filter %FUN :buffer %BUFFER
:timeout %FLOAT :start-time %FLOAT
:info %SEXP)")
(defvar org-async--wait-queue nil
"List of async queued task forms.
Each queued task is represented by a list with the following structure:
(%PROCESS :success %FUN :failure %FUN
:filter %FUN :buffer %BUFFER
:info %SEXP :dir %STRING
:timeout %FLOAT :coding %SYMBOL)")
(defvar org-async-process-limit 4
"Maximum number of processes to run at once.")
(defvar org-async-timeout 120
"Default timeout for a process started via `org-async-queue'.")
(defvar org-async-check-timeout-interval 1
"Check for processes which have exceeded their timeout every this many seconds.")
(defvar org-async--counter 0)
(cl-defun org-async-call (proc &key success failure filter buffer info timeout now process-variables
(dir default-directory) (coding 'utf-8))
"Start PROC and register it with callbacks SUCCESS and FAILURE.
PROC can be a process, string, or list. A string will be run as
a shell command, with `start-process-shell-command' and a list
run using `start-process' with the car as the command and the cdr
as the arguments. The process will be executed in DIR (if set)
or `default-directory'.
There is also a \"special form\" of PROC, namely a list where the
first item is the symbol org-async-task, and the rest constitutes
an argument list for `org-async-call'. This form allows for easy
specification of callbacks that are themselves async tasks, e.g.
(org-async-call \\='(\"sleep 1\")
:success \\='(org-async-task (\"notify-send\" \"done\")))
When using this form, all other arguments are ignored.
When BUFFER is provided, the output of PROC will be directed to it.
Shoud BUFFER be t, then a temp buffer will be created and removed
during `org-async--cleanup-process'.
SUCCESS and FAILURE can be any form accepted by `org-async--execute-callback',
namely:
- A string, which is used a `message' string with the exit-code,
process-buffer, and INFO as arguments.
- A function, which is called with exit-code, process-buffer,
and INFO as arguments.
- A list, which is used as an argument list for a new `org-async-call' call.
- nil, which does nothing.
When PROC succeeds by exiting with an exit code of zero, the SUCCESS
callback will be run. Should PROC fail, or be killed, or the process
runs for more than TIMEOUT seconds, the FAILURE callback will be run.
A function FILTER can be provided, in which case it will be
called in the same manner as a normal procecss filter, however
the function FILTER will be called with INFO as a third argument.
i.e. the call signature is (content new-content-string INFO)
When BUFFER is non-nil, there are two other major differences:
- The new content is silently inserted before FILTER is called
- Note that `point' is left alone and is not moved by this.
- The process buffer is the current buffer when FILTER is called.
When CODING is non-nil, both the process encode and decode system
will be set to CODING. If unset, UTF-8 is used.
When NOW is non-nil, the PROC is started immediately, regardless
of `org-async-process-limit'.
For improved performance, PROCESS-VARIABLES is a list of
let-style bindings that should be applied to the process.
Variables are supported on an individual basis (i.e. only certain
variables can be set), with the default value being equivalent to:
:process-variables ((process-adaptive-read-buffering nil)
(process-connection-type nil)
(read-process-output-max 65536))"
(cond
;; Called with a task (as can be used with callbacks), so re-call
;; with expanded arguments.
((and (consp proc)
(eq (car proc) 'org-async-task))
(apply #'org-async-call (cdr proc)))
;; Start the async process now.
((or now (< (length org-async--stack) org-async-process-limit))
(let ((proc
(let ((default-directory (or dir default-directory))
(process-adaptive-read-buffering ; No by default
(cadr (or (assoc 'process-adaptive-read-buffering process-variables) nil)))
(process-connection-type ; Use a pipe by default
(cadr (or (assoc 'process-connection-type process-variables) nil)))
(read-process-output-max ; Can be worth changing depending on the process
(or (assq 'read-process-output-max process-variables) read-process-output-max)))
(cond ((processp proc) proc)
((stringp proc)
(start-process-shell-command
(format "org-async-%d" (cl-incf org-async--counter))
buffer proc))
((consp proc)
(apply #'start-process
(format "org-async-%s-%d"
(car proc) (cl-incf org-async--counter))
buffer proc))
(t (error "Async process input %S not a recognised format"
proc)))))
(timeout (or timeout org-async-timeout)))
(set-process-sentinel proc #'org-async--sentinel)
(when filter
(set-process-filter proc #'org-async--filter))
(when coding
(set-process-coding-system proc coding coding))
(push (list proc
:success success
:failure failure
:filter filter
:buffer (if (eq buffer t)
(cons :temp (generate-new-buffer " *temp*" t))
buffer)
:info info
:timeout timeout
:start-time (float-time))
org-async--stack)
(org-async--monitor t)
(car org-async--stack)))
;; Queue the task to be run later.
(t
(setq org-async--wait-queue
(append org-async--wait-queue
(list (list proc
:success success
:failure failure
:filter filter
:buffer buffer
:info info
:dir dir
:timeout timeout
:coding coding))))
(last org-async--wait-queue))))
(defvar org-async--blocking-tasks nil
"List of async tasks currently being waited on.")
(defun org-async-wait-for (&rest tasks)
"Block until every task of TASKS has finished (including callback tasks)."
(setq org-async--blocking-tasks tasks)
(while org-async--blocking-tasks
(dolist (task org-async--blocking-tasks)
(accept-process-output (car task)))))
(defun org-async--filter (process string)
"After PROCESS recieves STRING, call the async filter.
This is implementated to satisfy the filter function documentation in
`org-async-call'."
(when-let ((proc-info (alist-get process org-async--stack)))
(let ((filter (plist-get proc-info :filter))
(buffer (plist-get proc-info :buffer)))
(if buffer
(with-current-buffer buffer
(save-excursion
(goto-char (point-max))
(insert string))
(funcall filter process string (plist-get proc-info :info)))
(funcall filter process string (plist-get proc-info :info))))))
(defun org-async--sentinel (process _signal)
"Watch PROCESS for death, and cleanup accordingly.
When a signal is recieved, the status of PROCESS is checked.
Should the it have an exit status, with status code 0,
`org-async--cleanup-process' is run with the \"failed\" argument
unset. Should the process have finished in any other manner,
`org-async--cleanup-process' is run with the \"failed\" argument."
(pcase (process-status process)
((and 'exit (guard (= 0 (process-exit-status process))))
(org-async--cleanup-process process))
((or 'exit 'signal 'failed)
(org-async--cleanup-process process 'failed))))
(defun org-async--cleanup-process (process &optional failed)
"Remove PROCESS from the async stack, and run its callback.
If the exit code of PROCESS is zero and FAILED is non-nil, then
the success callback is run (via `org-async--execute-callback').
Otherwise, the failure callback is run."
(when (assq process org-async--stack)
(let* ((proc-info (cdr (assq process org-async--stack)))
(buffer-val (plist-get proc-info :buffer))
(proc-buf (if (consp buffer-val) (cdr buffer-val) buffer-val))
(blocking-p (cl-member process org-async--blocking-tasks :key #'car)))
(setq org-async--stack
(delq (assq process org-async--stack) org-async--stack))
;; Ensure that any filter is called on the final output
;; prior to the callbacks.
(while (accept-process-output process))
(org-async--execute-callback
(plist-get
proc-info
(if (and (not failed)
(= 0 (process-exit-status process)))
:success :failure))
(process-exit-status process)
proc-buf
(plist-get proc-info :info)
blocking-p)
(when blocking-p
(setq org-async--blocking-tasks
(cl-delete process org-async--blocking-tasks :key #'car)))
(when (and (consp buffer-val) (eq :temp (car buffer-val)))
(kill-buffer proc-buf)))
(when (and org-async--wait-queue
(< org-async-process-limit (length org-async--stack)))
(apply #'org-async-call (pop org-async--wait-queue)))))
(defun org-async--execute-callback (callback exit-code process-buffer info &optional blocking)
"Run CALLBACK with EXIT-CODE, PROCESS-BUFFER, and INFO.
CALLBACK can take one of four forms:
- A string, which is used a `message' string with EXIT-CODE,
PROCESS-BUFFER, and INFO as arguments.
- A function, which is called with EXIT-CODE, PROCESS-BUFFER,
and INFO as arguments.
- A list, which is either:
- An (org-async-task ...) structure, which passed to an
`org-async-call' invocation.
- A list of callbacks, which are individually evaluated.
- nil, which does nothing.
When BLOCKING is set, all callback tasks are made blocking."
(cond
((stringp callback)
(message callback exit-code process-buffer info))
((functionp callback)
(funcall callback exit-code process-buffer info))
((consp callback)
(if (eq (car callback) 'org-async-task)
(if blocking
(push (org-async-call callback) org-async--blocking-tasks)
(org-async-call callback))
(dolist (clbk callback)
(org-async--execute-callback clbk exit-code process-buffer info blocking))))
((null callback)) ; Do nothing.
(t (message "Ignoring invalid `org-async-call' callback: %S" callback))))
(defvar org-async--monitor-scheduled nil)
(defun org-async--monitor (&optional force)
"Check each process against their timeouts, and kill any overdue.
The only runs when `org-async--monitor-scheduled' is nil, unless FORCE is set.
Should any processes still be alive after checking the stack, this will run
itself using a timer in `org-async-check-timeout-interval' seconds."
(when (or force (null org-async--monitor-scheduled))
(dolist (stack-proc org-async--stack)
(if (process-live-p (car stack-proc))
(let ((timeout (plist-get (cdr stack-proc) :timeout)))
(when (and (numberp timeout)
(< 0 timeout
(- (float-time)
(plist-get (cdr stack-proc) :start-time))))
(kill-process (car stack-proc))))
(org-async--cleanup-process (car stack-proc))))
(if org-async--stack
(setq org-async--monitor-scheduled
(run-at-time org-async-check-timeout-interval
nil #'org-async--monitor t))
(setq org-async--monitor-scheduled nil))))
;;; File
@ -377,6 +674,8 @@ in target-prerequisite files relation."
(defun org-do-remove-indentation (&optional n skip-fl)
"Remove the maximum common indentation from the buffer.
Do not consider invisible text when calculating indentation.
When optional argument N is a positive integer, remove exactly
that much characters from indentation, if possible. When
optional argument SKIP-FL is non-nil, skip the first
@ -397,7 +696,8 @@ line. Return nil if it fails."
;; Remove exactly N indentation, but give up if not possible.
(when skip-fl (forward-line))
(while (not (eobp))
(let ((ind (progn (skip-chars-forward " \t") (current-column))))
(let* ((buffer-invisibility-spec nil) ; do not treat invisible text specially
(ind (progn (skip-chars-forward " \t") (current-column))))
(cond ((< ind n)
(if (eolp) (delete-region (line-beginning-position) (point))
(throw :exit nil)))
@ -545,6 +845,7 @@ is selected, only the bare key is returned."
;; selection prefix.
((assoc current specials) (throw 'exit current))
(t (error "No entry available")))))))
(quit-window)
(when buffer (kill-buffer buffer))))))

View File

@ -602,22 +602,27 @@ MISC, if non-nil will be appended to the collection. It must be a plist."
;;;; Reading container data.
(defvar org-persist--inhibit-container-normalization nil
"Prevent `org-persist--normalize-container' from doing anything.")
(defun org-persist--normalize-container (container &optional inner)
"Normalize CONTAINER representation into (type . settings).
When INNER is non-nil, do not try to match as list of containers."
(pcase container
((or `elisp `elisp-data `version `file `index `url)
`(,container nil))
((or (pred keywordp) (pred stringp) `(quote . ,_))
`(elisp-data ,container))
((pred symbolp)
`(elisp ,container))
(`(,(or `elisp `elisp-data `version `file `index `url) . ,_)
container)
((and (pred listp) (guard (not inner)))
(mapcar (lambda (c) (org-persist--normalize-container c 'inner)) container))
(_ (error "org-persist: Unknown container type: %S" container))))
(if org-persist--inhibit-container-normalization
container
(pcase container
((or `elisp `elisp-data `version `file `index `url)
`(,container nil))
((or (pred keywordp) (pred stringp) `(quote . ,_))
`(elisp-data ,container))
((pred symbolp)
`(elisp ,container))
(`(,(or `elisp `elisp-data `version `file `index `url) . ,_)
container)
((and (pred listp) (guard (not inner)))
(mapcar (lambda (c) (org-persist--normalize-container c 'inner)) container))
(_ (error "org-persist: Unknown container type: %S" container)))))
(defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
"Buffer hash cache.")
@ -823,20 +828,23 @@ COLLECTION is the plist holding data collection."
(defun org-persist-write:file (c collection)
"Write file container C according to COLLECTION."
(org-persist-collection-let collection
(when (or (and path (file-exists-p path))
(and (stringp (cadr c)) (file-exists-p (cadr c))))
(when (and (stringp (cadr c)) (file-exists-p (cadr c)))
(setq path (cadr c)))
(let* ((persist-file (plist-get collection :persist-file))
(ext (file-name-extension path))
(file-copy (org-file-name-concat
org-persist-directory
(format "%s-%s.%s" persist-file (md5 path) ext))))
(unless (file-exists-p file-copy)
(unless (file-exists-p (file-name-directory file-copy))
(make-directory (file-name-directory file-copy) t))
(copy-file path file-copy 'overwrite))
(format "%s-%s.%s" persist-file (md5 path) ext)))))
(if (or (and path (file-exists-p path))
(and (stringp (cadr c)) (file-exists-p (cadr c))))
(progn
(when (and (stringp (cadr c)) (file-exists-p (cadr c)))
(setq path (cadr c)))
(let* ((persist-file (plist-get collection :persist-file))
(ext (file-name-extension path))
(file-copy (org-file-name-concat
org-persist-directory
(format "%s-%s.%s" persist-file (md5 path) ext))))
(unless (file-exists-p file-copy)
(unless (file-exists-p (file-name-directory file-copy))
(make-directory (file-name-directory file-copy) t))
(copy-file path file-copy 'overwrite))
(format "%s-%s.%s" persist-file (md5 path) ext)))
(when-let ((file-copy (org-persist-read c associated)))
(file-relative-name file-copy org-persist-directory)))))
(defun org-persist-write:url (c collection)
"Write url container C according to COLLECTION."
@ -857,22 +865,31 @@ COLLECTION is the plist holding data collection."
path)))
(format "%s-%s.%s" persist-file (md5 path) ext)))))
(defun org-persist--check-write-access (path)
"Check write access to all missing directories in PATH.
Show message and return nil if there is no write access.
Otherwise, return t."
(let* ((dir (directory-file-name (file-name-as-directory path)))
(prev dir))
(while (and (not (file-exists-p dir))
(setq prev dir)
(not (equal dir (setq dir (directory-file-name
(file-name-directory dir)))))))
(if (file-writable-p prev) t ; return t
(message "org-persist: Missing write access rights to: %S" prev)
;; return nil
nil)))
(defun org-persist-write:index (container _)
"Write index CONTAINER."
(org-persist--get-collection container)
(unless (file-exists-p org-persist-directory)
(make-directory org-persist-directory))
(unless (file-exists-p org-persist-directory)
(warn "Failed to create org-persist storage in %s."
org-persist-directory)
(let ((dir (directory-file-name
(file-name-as-directory org-persist-directory))))
(while (and (not (file-exists-p dir))
(not (equal dir (setq dir (directory-file-name
(file-name-directory dir)))))))
(unless (file-writable-p dir)
(message "Missing write access rights to org-persist-directory: %S"
org-persist-directory))))
(condition-case nil
(make-directory org-persist-directory 'parent)
(t
(warn "Failed to create org-persist storage in %s."
org-persist-directory)
(org-persist--check-write-access org-persist-directory))))
(when (file-exists-p org-persist-directory)
(let ((index-file
(org-file-name-concat org-persist-directory org-persist-index-file)))
@ -941,26 +958,27 @@ VALUE pairs.
When WRITE-IMMEDIATELY is non-nil, the return value will be the same
with `org-persist-write'."
(unless org-persist--index (org-persist--load-index))
(setq container (org-persist--normalize-container container))
(when inherit
(setq inherit (org-persist--normalize-container inherit))
(let ((inherited-collection (org-persist--get-collection inherit associated))
new-collection)
(unless (member container (plist-get inherited-collection :container))
(setq new-collection
(plist-put (copy-sequence inherited-collection) :container
(cons container (plist-get inherited-collection :container))))
(org-persist--remove-from-index inherited-collection)
(org-persist--add-to-index new-collection))))
(let ((collection (org-persist--get-collection container associated misc)))
(when (and expiry (not inherit))
(when expiry (plist-put collection :expiry expiry))))
(when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
(with-current-buffer (if (bufferp associated)
associated
(plist-get associated :buffer))
(add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local)))
(when write-immediately (org-persist-write container associated)))
(let ((container (org-persist--normalize-container container))
(inherit (and inherit (org-persist--normalize-container inherit)))
(org-persist--inhibit-container-normalization t))
(when inherit
(let ((inherited-collection (org-persist--get-collection inherit associated))
new-collection)
(unless (member container (plist-get inherited-collection :container))
(setq new-collection
(plist-put (copy-sequence inherited-collection) :container
(cons container (plist-get inherited-collection :container))))
(org-persist--remove-from-index inherited-collection)
(org-persist--add-to-index new-collection))))
(let ((collection (org-persist--get-collection container associated misc)))
(when (and expiry (not inherit))
(when expiry (plist-put collection :expiry expiry))))
(when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
(with-current-buffer (if (bufferp associated)
associated
(plist-get associated :buffer))
(add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local)))
(when write-immediately (org-persist-write container associated))))
(cl-defun org-persist-unregister (container &optional associated &key remove-related)
"Unregister CONTAINER in ASSOCIATED to be persistent.
@ -1075,6 +1093,9 @@ have the same meaning as in `org-persist-read'."
"Call `org-persist-load-all' in current buffer."
(org-persist-load-all (current-buffer)))
(defvar org-persist--inhibit-write nil
"Whether `org-persist-write' should be inhibited.")
(defun org-persist-write (container &optional associated ignore-return)
"Save CONTAINER according to ASSOCIATED.
ASSOCIATED can be a plist, a buffer, or a string.
@ -1084,31 +1105,33 @@ The return value is nil when writing fails and the written value (as
returned by `org-persist-read') on success.
When IGNORE-RETURN is non-nil, just return t on success without calling
`org-persist-read'."
(setq associated (org-persist--normalize-associated associated))
;; Update hash
(when (and (plist-get associated :file)
(plist-get associated :hash)
(get-file-buffer (plist-get associated :file)))
(setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
(let ((collection (org-persist--get-collection container associated)))
(setf collection (plist-put collection :associated associated))
(unless (or
;; Prevent data leakage from encrypted files.
;; We do it in somewhat paranoid manner and do not
;; allow anything related to encrypted files to be
;; written.
(and (plist-get associated :file)
(string-match-p epa-file-name-regexp (plist-get associated :file)))
(seq-find (lambda (v)
(run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
(plist-get collection :container)))
(when (or (file-exists-p org-persist-directory) (org-persist--save-index))
(let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
(data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
(plist-get collection :container))))
(puthash file data org-persist--write-cache)
(org-persist--write-elisp-file file data)
(or ignore-return (org-persist-read container associated)))))))
(unless org-persist--inhibit-write
(setq associated (org-persist--normalize-associated associated))
;; Update hash
(when (and (plist-get associated :file)
(plist-get associated :hash)
(get-file-buffer (plist-get associated :file)))
(setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
(let ((collection (org-persist--get-collection container associated))
(org-persist--inhibit-write t))
(setf collection (plist-put collection :associated associated))
(unless (or
;; Prevent data leakage from encrypted files.
;; We do it in somewhat paranoid manner and do not
;; allow anything related to encrypted files to be
;; written.
(and (plist-get associated :file)
(string-match-p epa-file-name-regexp (plist-get associated :file)))
(cl-some (lambda (v)
(run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
(plist-get collection :container)))
(when (or (file-exists-p org-persist-directory) (org-persist--save-index))
(let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
(data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
(plist-get collection :container))))
(puthash file data org-persist--write-cache)
(org-persist--write-elisp-file file data)
(or ignore-return (org-persist-read container associated))))))))
(defun org-persist-write-all (&optional associated)
"Save all the persistent data.
@ -1294,19 +1317,12 @@ such scenario."
(make-temp-file "org-persist-" 'dir)))
;; Automatically write the data, but only when we have write access.
(let ((dir (directory-file-name
(file-name-as-directory org-persist-directory))))
(while (and (not (file-exists-p dir))
(not (equal dir (setq dir (directory-file-name
(file-name-directory dir)))))))
(if (not (file-writable-p dir))
(message "Missing write access rights to org-persist-directory: %S"
org-persist-directory)
(add-hook 'kill-emacs-hook #'org-persist-clear-storage-maybe) ; Run last.
(add-hook 'kill-emacs-hook #'org-persist-write-all)
;; `org-persist-gc' should run before `org-persist-write-all'.
;; So we are adding the hook after `org-persist-write-all'.
(add-hook 'kill-emacs-hook #'org-persist-gc)))
(when (org-persist--check-write-access org-persist-directory)
(add-hook 'kill-emacs-hook #'org-persist-clear-storage-maybe) ; Run last.
(add-hook 'kill-emacs-hook #'org-persist-write-all)
;; `org-persist-gc' should run before `org-persist-write-all'.
;; So we are adding the hook after `org-persist-write-all'.
(add-hook 'kill-emacs-hook #'org-persist-gc))
(add-hook 'after-init-hook #'org-persist-load-all)

View File

@ -541,8 +541,7 @@ prefix argument (`C-u C-u C-u C-c C-w')."
(< 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)))
(setq nbuf (find-file-noselect file 'nowarn))
(if (and arg (not (equal arg 3)))
(progn
(pop-to-buffer-same-window nbuf)
@ -562,8 +561,7 @@ prefix argument (`C-u C-u C-u C-c C-w')."
;; will then remain before the inserted subtree in
;; unexpected location.
(set-marker-insertion-type origin t)
(with-current-buffer (setq nbuf (or (find-buffer-visiting file)
(find-file-noselect file)))
(with-current-buffer (setq nbuf (find-file-noselect file 'nowarn))
(setq reversed (org-notes-order-reversed-p))
(org-with-wide-buffer
(if pos
@ -727,8 +725,7 @@ this function appends the default value from
(when (org-string-nw-p re)
(setq buffer (if (markerp pos)
(marker-buffer pos)
(or (find-buffer-visiting file)
(find-file-noselect file))))
(find-file-noselect file 'nowarn)))
(with-current-buffer buffer
(org-with-wide-buffer
(goto-char pos)
@ -743,8 +740,7 @@ this function appends the default value from
(let ((file (nth 1 parent-target))
(pos (nth 3 parent-target))
level)
(with-current-buffer (or (find-buffer-visiting file)
(find-file-noselect file))
(with-current-buffer (find-file-noselect file 'nowarn)
(org-with-wide-buffer
(if pos
(goto-char pos)
@ -779,6 +775,14 @@ this function appends the default value from
(concat string (substring r 0 (match-end 0)) f)
x)))
(all-completions string thetable predicate))))
((eq (car-safe flag) 'boundaries)
;; See `completion-file-name-table'.
(let ((start (or (and (string-match "/" string)
(match-beginning 0))
(length string)))
(end (and (string-match "/" (cdr flag))
(match-beginning 0))))
`(boundaries ,start . ,end)))
;; Exact match?
((eq flag 'lambda) (assoc string thetable))))
args)))

View File

@ -681,7 +681,9 @@ as `org-src-fontify-natively' is non-nil."
(unless (eq major-mode lang-mode) (funcall lang-mode))
(setq native-tab-width tab-width)
(font-lock-ensure)
(let ((pos (point-min)) next)
(let ((pos (point-min)) next
;; Difference between positions here and in org-buffer.
(offset (- start (point-min))))
(while (setq next (next-property-change pos))
;; Handle additional properties from font-lock, so as to
;; preserve, e.g., composition.
@ -695,7 +697,7 @@ as `org-src-fontify-natively' is non-nil."
(when new-prop
(if (not (eq prop 'invisible))
(put-text-property
(+ start (1- pos)) (1- (+ start next)) prop new-prop
(+ offset pos) (+ offset next) prop new-prop
org-buffer)
;; Special case. `invisible' text property may
;; clash with Org folding. Do not assign
@ -727,7 +729,7 @@ as `org-src-fontify-natively' is non-nil."
(when invisibility-spec
(add-to-invisibility-spec invisibility-spec))
(put-text-property
(+ start (1- pos)) (1- (+ start next))
(+ offset pos) (+ offset next)
'org-src-invisible new-prop
org-buffer)))))))
(setq pos next)))
@ -776,12 +778,9 @@ as `org-src-fontify-natively' is non-nil."
(lang-beg (match-beginning 1))
(lang-end (match-end 1))
pt)
(font-lock-append-text-property
lang-beg lang-end 'face 'org-meta-line)
(font-lock-append-text-property
beg lang-beg 'face 'shadow)
(font-lock-append-text-property
beg lang-end 'face 'org-inline-src-block)
(add-face-text-property beg lang-end 'org-inline-src-block)
(add-face-text-property beg lang-beg 'shadow)
(add-face-text-property lang-beg lang-end 'org-meta-line)
(setq pt (goto-char lang-end))
;; `org-element--parse-paired-brackets' doesn't take a limit, so to
;; prevent it searching the entire rest of the buffer we temporarily
@ -793,13 +792,11 @@ as `org-src-fontify-natively' is non-nil."
(point)))
(point-max))))
(when (ignore-errors (org-element--parse-paired-brackets ?\[))
(font-lock-append-text-property
pt (point) 'face 'org-inline-src-block)
(add-face-text-property pt (point) 'org-inline-src-block)
(setq pt (point)))
(when (ignore-errors (org-element--parse-paired-brackets ?\{))
(remove-text-properties pt (point) '(face nil))
(font-lock-append-text-property
pt (1+ pt) 'face '(org-inline-src-block shadow))
(add-face-text-property pt (1+ pt) '(org-inline-src-block shadow))
(unless (= (1+ pt) (1- (point)))
(if org-src-fontify-natively
(org-src-font-lock-fontify-block
@ -807,11 +804,44 @@ as `org-src-fontify-natively' is non-nil."
(1+ pt) (1- (point)))
(font-lock-append-text-property
(1+ pt) (1- (point)) 'face 'org-inline-src-block)))
(font-lock-append-text-property
(add-face-text-property
(1- (point)) (point) 'face '(org-inline-src-block shadow))
(setq pt (point)))))
(setq pt (point)))
(when (and org-inline-src-prettify-results
(re-search-forward "\\= {{{results(" limit t))
(font-lock-append-text-property pt (1+ pt) 'face 'org-inline-src-block)
(goto-char pt))))
t)))
(defun org-fontify-inline-src-results (limit)
"Apply prettify-symbols modifications to inline results blocks.
Performed according to `org-inline-src-prettify-results'."
(when (and org-inline-src-prettify-results
(re-search-forward "{{{results(\\(.+?\\))}}}" limit t))
(remove-list-of-text-properties (match-beginning 0) (point)
'(composition
prettify-symbols-start
prettify-symbols-end))
(font-lock-append-text-property (match-beginning 0) (match-end 0)
'face 'org-block)
(let ((start (match-beginning 0)) (end (match-beginning 1)))
(with-silent-modifications
(compose-region start end (if (eq org-inline-src-prettify-results t)
"(" (car org-inline-src-prettify-results)))
(add-text-properties start end `(prettify-symbols-start ,start prettify-symbols-end ,end))))
(let ((start (match-end 1)) (end (point)))
(with-silent-modifications
(compose-region start end (if (eq org-inline-src-prettify-results t)
")" (cdr org-inline-src-prettify-results)))
(add-text-properties start end `(prettify-symbols-start ,start prettify-symbols-end ,end))))
t))
(defun org-toggle-inline-results-display ()
"Toggle the literal or contracted display of inline src blocks results."
(interactive)
(setq org-inline-src-prettify-results (not org-inline-src-prettify-results))
(org-restart-font-lock))
;;; Escape contents

View File

@ -1142,7 +1142,8 @@ With numeric argument N, move N-1 fields forward first."
;;;###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."
When next row is an hline or outside the table, create a new empty
row. Before doing so, re-align the table if necessary."
(interactive)
(org-table-maybe-eval-formula)
(org-table-maybe-recalculate-line)

File diff suppressed because it is too large Load Diff

View File

@ -429,8 +429,21 @@ used as a communication channel."
;; among `org-beamer-verbatim-elements'.
(org-element-map headline org-beamer-verbatim-elements 'identity
info 'first-match))
(frame (or (and fragilep org-beamer-frame-environment)
"frame")))
;; If FRAGILEP is non-nil and CONTENTS contains an occurrence
;; of \begin{frame} or \end{frame}, then set the FRAME
;; environment to be `org-beamer-frame-environment';
;; otherwise, use "frame". If the selected environment is not
;; "frame", then add the property :beamer-define-frame to
;; INFO and set it to t.
(frame (let ((selection
(or (and fragilep
(or (string-match-p "\\\\begin{frame}" contents)
(string-match-p "\\\\end{frame}" contents))
org-beamer-frame-environment)
"frame")))
(unless (string= selection "frame")
(setq info (plist-put info :beamer-define-frame t)))
selection)))
(concat "\\begin{" frame "}"
;; Overlay specification, if any. When surrounded by
;; square brackets, consider it as a default
@ -847,12 +860,10 @@ holding export options."
;; Timestamp.
(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.
;; Document class, packages, and some configuration.
(org-latex-make-preamble info)
;; Define the alternative frame environment.
(unless (equal "frame" org-beamer-frame-environment)
;; Define the alternative frame environment, if needed.
(when (plist-get info :beamer-define-frame)
(format "\\newenvironment<>{%s}[1][]{\\begin{frame}#2[environment=%1$s,#1]}{\\end{frame}}\n"
org-beamer-frame-environment))
;; Insert themes.
@ -902,12 +913,6 @@ holding export options."
(let ((template (plist-get info :latex-hyperref-template)))
(and (stringp template)
(format-spec template (org-latex--format-spec info))))
;; engrave-faces-latex preamble
(when (and (eq (plist-get info :latex-src-block-backend) 'engraved)
(org-element-map (plist-get info :parse-tree)
'(src-block inline-src-block) #'identity
info t))
(org-latex-generate-engraved-preamble info))
;; Document start.
"\\begin{document}\n\n"
;; Title command.

View File

@ -39,6 +39,8 @@
(require 'ox)
(require 'ox-publish)
(require 'table)
(require 'org-latex-preview)
(require 'ox-mathml)
;;; Function Declarations
@ -107,7 +109,8 @@
(verbatim . org-html-verbatim)
(verse-block . org-html-verse-block))
:filters-alist '((:filter-options . org-html-infojs-install-script)
(:filter-parse-tree . org-html-image-link-filter)
(:filter-parse-tree org-html-image-link-filter
org-html-prepare-latex-images)
(:filter-final-output . org-html-final-function))
:menu-entry
'(?h "Export to HTML"
@ -155,6 +158,7 @@
(: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-latex-image-options nil nil org-html-latex-image-options)
(: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)
@ -270,7 +274,7 @@ This affects IDs that are determined from the ID property.")
:type 'string)
(defcustom org-html-style-default
"<style>
"<style type=\"text/css\">
#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
@ -319,7 +323,7 @@ This affects IDs that are determined from the ID property.")
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-C\\+\\+:before { content: 'C++'; }
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
@ -822,7 +826,7 @@ e.g. \"tex:mathjax\". Allowed values are:
be loaded.
`html' Use `org-latex-to-html-convert-command' to convert
LaTeX fragments to HTML.
SYMBOL Any symbol defined in `org-preview-latex-process-alist',
SYMBOL Any symbol defined in `org-latex-preview-process-alist',
e.g., `dvipng'."
:group 'org-export-html
:version "24.4"
@ -861,15 +865,15 @@ link to the image."
:type 'boolean)
(defcustom org-html-inline-image-rules
`(("file" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp")))
("http" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp")))
("https" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp"))))
`(("file" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp" ".avif")))
("http" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp" ".avif")))
("https" . ,(regexp-opt '(".jpeg" ".jpg" ".png" ".gif" ".svg" ".webp" ".avif"))))
"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
:package-version '(Org . "9.5")
:package-version '(Org . "9.7")
:type '(alist :key-type (string :tag "Type")
:value-type (regexp :tag "Path")))
@ -1168,6 +1172,25 @@ See `format-time-string' for more information on its components."
:package-version '(Org . "8.0")
:type 'string)
(defcustom org-html-latex-image-options
'(:foreground "Black" :background "Transparent"
:page-width 1.0 :scale 1.0 :image-dir "ltximg" :inline nil)
"LaTeX preview options that apply to generated images.
This is a HTML-specific counterpart to
`org-latex-preview-appearance-options', which see.
This supports two extra properties,
:image-dir an html-export counterpart of `org-latex-preview-cache', and
:inline a list of image formats (or single format symbol) that
should not be saved according to :image-dir, but instead
inlined in the generated HTML. Valid format symbols are:
- png, to inline png images using <img> with a data URI
- svg, to inline svg images using <img> with a data URI
- svg-embed, to inline svg images using an <svg> element"
:group 'org-export-html
:package-version '(Org . "9.7")
:type 'plist)
;;;; Template :: Mathjax
(defcustom org-html-mathjax-options
@ -1653,6 +1676,33 @@ https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag"
:package-version '(Org . "9.1")
:type 'string)
;;;; LaTeX Fragments
(defcustom org-latex-to-html-convert-command nil
"Shell command to convert LaTeX fragments to HTML.
This command is very open-ended: the output of the command will
directly replace the LaTeX fragment in the resulting HTML.
Replace format-specifiers in the command as noted below and use
`shell-command' to convert LaTeX to HTML.
%i: The LaTeX fragment to be converted (shell-escaped).
It must not be used inside a quoted argument, the result of %i
expansion inside a quoted argument is undefined.
For example, this could be used with LaTeXML as
\"latexmlc literal:%i --profile=math --preload=siunitx.sty 2>/dev/null\"."
:group 'org-latex
:package-version '(Org . "9.4")
:type '(choice
(const :tag "None" nil)
(string :tag "Shell command")))
(defun org-format-latex-as-html (latex-fragment)
"Convert LATEX-FRAGMENT to HTML.
This uses `org-latex-to-html-convert-command', which see."
(let ((cmd (format-spec org-latex-to-html-convert-command
`((?i . ,latex-fragment)))))
(message "Running %s" cmd)
(shell-command-to-string cmd)))
;;;; Todos
@ -1777,11 +1827,7 @@ a communication channel."
(org-html--make-attribute-string
(org-combine-plists
(list :src source
:alt (if (string-match-p
(concat "^" org-preview-latex-image-directory) source)
(org-html-encode-plain-text
(org-find-text-property-in-string 'org-latex-src source))
(file-name-nondirectory source)))
:alt (file-name-nondirectory source))
(if (string= "svg" (file-name-extension source))
(org-combine-plists '(:class "org-svg") attributes '(:fallback nil))
attributes)))
@ -2994,58 +3040,102 @@ CONTENTS is nil. INFO is a plist holding contextual information."
;;;; 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', `html', 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 (or (eq processing-type 'mathjax)
(eq processing-type 'html))
(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))))
(org-export-with-buffer-copy
:to-buffer (get-buffer-create " *Org HTML Export LaTeX*")
:drop-visibility t :drop-narrowing t :drop-contents t
(erase-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-prepare-latex-images (parse-tree _backend info)
"Make sure that appropriate preview images exist for all LaTeX.
TODO."
(when (assq (plist-get info :with-latex) org-latex-preview-process-alist)
(let* ((latex-preamble
(or org-latex-preview--preamble-content
(setq org-latex-preview--preamble-content
(org-latex-preview--get-preamble))))
(elements
(org-element-map parse-tree
'(latex-fragment latex-environment)
#'identity
info))
(entries-and-numbering
(org-latex-preview--construct-entries
elements t parse-tree))
(processing-type (plist-get info :with-latex))
(processing-info
(cdr (assq processing-type org-latex-preview-process-alist)))
(imagetype (or (plist-get processing-info :image-output-type) "png"))
(numbering-offsets (cons nil (cadr entries-and-numbering)))
(html-options (plist-get info :html-latex-image-options))
(element-hash-table (make-hash-table :test #'eq :size (length elements)))
fragment-info prev-fg prev-bg)
(cl-loop
for entry in (car entries-and-numbering)
for element in elements
do
(pcase-let* ((`(,beg ,end ,provided-value) entry)
(value (or provided-value
(buffer-substring-no-properties beg end)))
(fg (plist-get html-options :foreground))
(bg (plist-get html-options :background))
(number (car (setq numbering-offsets (cdr numbering-offsets))))
(hash (org-latex-preview--hash
processing-type latex-preamble value imagetype fg bg number))
(options (org-combine-plists
org-latex-preview-appearance-options
html-options
(list :number number
:continue-color
(and (equal prev-bg bg)
(equal prev-fg fg))))))
(puthash element hash element-hash-table)
(unless (org-latex-preview--get-cached hash)
(push (list :string (org-latex-preview--tex-styled
processing-type value options)
:overlay (org-latex-preview--ensure-overlay beg end)
:key hash)
fragment-info))
(setq prev-fg fg prev-bg bg)))
(when fragment-info
(apply #'org-async-wait-for
(org-latex-preview--create-image-async
processing-type
(nreverse fragment-info)
:latex-preamble latex-preamble
:appearance-options html-options)))
(plist-put info :html-latex-preview-hash-table element-hash-table)
nil)))
(defun org-html--wrap-latex-environment (contents _ &optional caption label)
(defun org-html--as-latex (element info &optional content)
(let ((content (or content (org-element-property :value element))))
(pcase (plist-get info :with-latex)
('verbatim ; Do nothing.
content)
((or 't 'mathjax)
(cond ; Prepare for MathJax processing.
((string-match-p "\\`\\$\\$" content)
(concat "\\[" (substring content 2 -2) "\\]"))
((string-match-p "\\`\\$" content)
(concat "\\(" (substring content 1 -1) "\\)"))
(t content)))
('html
(org-format-latex-as-html content))
('mathml
(if-let ((path (org-mathml-convert-latex-cached content)))
(with-temp-buffer
(insert-file-contents path)
(buffer-string))
content))
((and ptype (guard (assq ptype org-latex-preview-process-alist)))
(org-html-latex-image element info))
(processing-type
(warn "LaTeX fragment processor `%s' is unknown" processing-type)
content))))
(defun org-html--wrap-latex-environment (contents &optional label)
"Wrap CONTENTS string within appropriate environment for equations.
When optional arguments CAPTION and LABEL are given, use them for
caption and \"id\" attribute."
(format "\n<div%s class=\"equation-container\">\n%s%s\n</div>"
(format "\n<div%s class=\"equation-container\">\n%s\n</div>"
;; ID.
(if (org-string-nw-p label) (format " id=\"%s\"" label) "")
;; Contents.
(format "<span class=\"equation\">\n%s\n</span>" contents)
;; Caption.
(if (not (org-string-nw-p caption)) ""
(format "\n<span class=\"equation-label\">\n%s\n</span>"
caption))))
(format "<span class=\"equation\">\n%s\n</span>" contents)))
(defun org-html--math-environment-p (element &optional _)
"Non-nil when ELEMENT is a LaTeX math environment.
@ -3077,57 +3167,141 @@ For instance, change an `equation' environment to `equation*'."
"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))
(label (org-html--reference latex-environment info t))
(caption (and (org-html--latex-environment-numbered-p latex-environment)
(number-to-string
(org-export-get-ordinal
latex-environment info nil
(lambda (l _)
(and (org-html--math-environment-p l)
(org-html--latex-environment-numbered-p l))))))))
(cond
((memq processing-type '(t mathjax))
(org-html-format-latex
(if (org-string-nw-p label)
(replace-regexp-in-string "\\`.*"
(format "\\&\n\\\\label{%s}" label)
latex-frag)
latex-frag)
'mathjax info))
((assq processing-type org-preview-latex-process-alist)
(let ((formula-link
(org-html-format-latex
(org-html--unlabel-latex-environment latex-frag)
processing-type info)))
(when (and formula-link (string-match "file:\\([^]]*\\)" formula-link))
(let ((source (org-export-file-uri (match-string 1 formula-link))))
(org-html--wrap-latex-environment
(org-html--format-image source attributes info)
info caption label)))))
(t (org-html--wrap-latex-environment latex-frag info caption label)))))
(latex-frag (org-remove-indentation
(org-element-property :value latex-environment)))
(label (org-html--reference latex-environment info t)))
(if (memq processing-type '(t mathjax))
(org-html--as-latex
latex-environment info
(if (org-string-nw-p label)
(replace-regexp-in-string "\\`.*"
(format "\\&\n\\\\label{%s}" label)
latex-frag)
latex-frag))
(org-html--wrap-latex-environment
(org-html--as-latex latex-environment info latex-frag)
label))))
;;;; 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)))
(org-html--as-latex latex-fragment info))
(defun org-html-latex-image (element info)
"Transcode the LaTeX fragment or environment ELEMENT from Org to HTML.
INFO is a plist holding contextual information, and it is assumed
that an image for ELEMENT already exists within it."
(let* ((hash (or (gethash element (plist-get info :html-latex-preview-hash-table))
(error "Expected LaTeX preview hash to exist for element, but none found")))
(path-info (or (org-latex-preview--get-cached hash)
(error "Expected LaTeX preview %S to exist in the cache" hash)))
(image-options (plist-get info :html-latex-image-options))
(block-p (memq (aref (org-element-property :value element) 1) '(?$ ?\[)))
(image-source
(org-html-latex-image--data path-info hash info block-p)))
(unless (and (plist-get (cdr path-info) :height)
(plist-get (cdr path-info) :depth))
(error "Something went wrong during image generation"))
(if (and (eq (plist-get image-options :inline) 'svg-embed)
(eq (plist-get (cdr path-info) :image-type) 'svg))
image-source
(let ((scaling (org-html-latex-image--scaling path-info info)))
(org-html-close-tag
"img"
(org-html--make-attribute-string
(list :src image-source
:alt (org-html-encode-plain-text
(org-element-property :value element))
:style (if block-p
(format "height: %.4fem; display: block" (plist-get scaling :height))
(format "height: %.4fem; vertical-align: -%.4fem; display: inline-block"
(plist-get scaling :height) (plist-get scaling :depth)))
:class (format "org-latex org-latex-%s" (if block-p "block" "inline"))))
info)))))
(defun org-html-latex-image--scaling (image-path-info info)
"Determine the appropriate (<height> . <depth>) of IMAGE-PATH-INFO given INFO."
(let* ((image-options (plist-get info :html-latex-image-options))
(rescale-factor (if (eq (plist-get (cdr image-path-info) :image-type) 'svg)
(plist-get image-options :scale)
1)))
(list :height (* rescale-factor (plist-get (cdr image-path-info) :height))
:depth (* rescale-factor (plist-get (cdr image-path-info) :depth)))))
(defun org-html-latex-image--data (image-path-info hash info &optional block-p)
"Obtaine the image source for IMAGE-PATH-INFO as a string.
This can take the form of a path, data URI, or <svg> element
depending on HASH and INFO. BLOCK-P signals that the image
should be a block element."
(let* ((image-options (plist-get info :html-latex-image-options))
(inline-condition (plist-get image-options :inline))
(image-dir (plist-get image-options :image-dir))
(image-format (plist-get (cdr image-path-info) :image-type))
(source-file (car image-path-info)))
(cond
((memq processing-type '(t mathjax))
(org-html-format-latex latex-frag 'mathjax info))
((memq processing-type '(t html))
(org-html-format-latex latex-frag 'html 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))
(let ((source (org-export-file-uri (match-string 1 formula-link))))
(org-html--format-image source nil info)))))
(t latex-frag))))
((or inline-condition
(member (file-name-extension source-file)
(org-ensure-list inline-condition)))
(let ((coding-system-for-read 'utf-8)
(file-name-handler-alist nil))
(with-temp-buffer
(insert-file-contents-literally source-file)
(cond
((and (eq inline-condition 'svg-embed)
(eq image-format 'svg))
(goto-char (point-min))
(let ((svg-closing-tag (and (search-forward "<svg" nil t)
(search-forward ">" nil t))))
(dolist (search '("<!-- This file was generated by dvisvgm [^\n]+ -->"
" height=['\"][^\"']+[\"']"
" width=['\"][^\"']+[\"']"))
(goto-char (point-min))
(when (re-search-forward search svg-closing-tag t)
(replace-match "")))
(goto-char (point-min))
(when (re-search-forward "viewBox=['\"][^\"']+[\"']" svg-closing-tag t)
(insert
" style=\""
(let ((scaling (org-html-latex-image--scaling image-path-info info)))
(if block-p
(format "height: %.4fem; display: block" (plist-get scaling :height))
(format "height: %.4fem; vertical-align: -%.4fem; display: inline-block"
(plist-get scaling :height) (plist-get scaling :depth))))
"\" class=\"org-latex org-latex-"
(if block-p "block" "inline")
"\"")))
(buffer-string))
((eq image-format 'svg)
;; Modelled after <https://codepen.io/tigt/post/optimizing-svgs-in-data-uris>.
(concat "data:image/svg+xml,"
(url-hexify-string
(subst-char-in-string ?\" ?\' (buffer-string))
'(?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n
?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A ?B
?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P
?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?0 ?1 ?2 ?3
?4 ?5 ?6 ?7 ?8 ?9 ?- ?_ ?. ?~
;;Special additions
?\s ?= ?: ?/))))
(t
(base64-encode-region (point-min) (point-max))
(goto-char (point-min))
(insert "data:image/" (symbol-name image-format) ";base64,")
(buffer-string))))))
((stringp image-dir)
(let* ((image-dir (expand-file-name image-dir))
(image-path (file-name-with-extension
(file-name-concat image-dir (substring hash 0 11))
(file-name-extension source-file))))
(unless (file-directory-p image-dir)
(mkdir image-dir t))
(unless (file-exists-p image-path)
(copy-file source-file image-path))
image-path))
(t source-file))))
;;;; Line Break
@ -3231,8 +3405,6 @@ INFO is a plist holding contextual information. See
(desc (org-string-nw-p desc))
(path
(cond
((member type '("http" "https" "ftp" "mailto" "news"))
(url-encode-url (concat type ":" raw-path)))
((string= "file" type)
;; During publishing, turn absolute file names belonging
;; to base directory into relative file names. Otherwise,
@ -3259,7 +3431,7 @@ INFO is a plist holding contextual information. See
(concat raw-path
"#"
(org-publish-resolve-external-link option path t))))))
(t raw-path)))
(t (url-encode-url (concat type ":" raw-path)))))
(attributes-plist
(org-combine-plists
;; Extract attributes from parent's paragraph. HACK: Only

View File

@ -48,6 +48,7 @@
(defvar engrave-faces-latex-output-style)
(defvar engrave-faces-current-preset-style)
(defvar engrave-faces-latex-mathescape)
(defvar engrave-faces-latex-colorbox-strut)
;;; Define Backend
@ -110,9 +111,9 @@
(?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)))))))
(lambda (async subtreep visable-only body-only)
(if async (org-latex-export-to-pdf t subtreep visable-only body-only)
(org-latex-export-to-pdf-and-open nil subtreep visable-only body-only))))))
: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
@ -170,7 +171,83 @@
(: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)))
(:date "DATE" nil "\\today" parse))
:feature-conditions-alist
`((t !announce-start !announce-end
!guess-pollyglossia !guess-babel !guess-inputenc)
(,(lambda (info)
;; Since amsmath is added unconditionally when using
;; xelatex/lualatex (see `org-latex-default-packages-alist'),
;; and amssymb is not needed, we need not bother when using
;; thoese compilers.
(and (not (member (plist-get info :latex-compiler) '("xelatex" "lualatex")))
(org-element-map (plist-get info :parse-tree)
'(latex-fragment latex-environment) #'identity info t)))
maths)
(,(lambda (info)
(org-element-map (plist-get info :parse-tree)
'underline #'identity info t))
underline)
("\\\\uu?line\\|\\\\uwave\\|\\\\sout\\|\\\\xout\\|\\\\dashuline\\|\\dotuline\\|\\markoverwith"
underline)
(,(lambda (info)
(org-element-map (plist-get info :parse-tree)
'link
(lambda (link)
(and (member (org-element-property :type link)
'("http" "https" "ftp" "file"))
(file-name-extension (org-element-property :path link))
(equal (downcase (file-name-extension
(org-element-property :path link)))
"svg")))
info t))
svg)
(org-latex-tables-booktabs booktabs)
(,(lambda (info)
(equal (plist-get info :latex-default-table-environment)
"longtable"))
longtable)
("^[ \t]*\\+attr_latex: .*:environment +longtable"
longtable)
(,(lambda (info)
(eq (plist-get info :latex-src-block-backend) 'engraved))
engraved-code)
("^[ \t]*#\\+attr_latex: .*:float +wrap"
float-wrap)
("^[ \t]*#\\+attr_latex: .*:float +sideways"
rotate)
("^[ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\|\\\\caption{" caption))
:feature-implementations-alist
`((!announce-start
:snippet ,(lambda (info)
(with-temp-buffer
(setq-local left-margin 2)
(insert (string-join
(mapcar #'symbol-name
(plist-get info :features))
", ")
".")
(fill-region-as-paragraph (point-min) (point-max))
(goto-char (point-min))
(insert "%% ox-latex features:\n% ")
(while (search-forward "\n" nil t)
(insert "%"))
(buffer-string)))
:order -100)
(maths :snippet "\\usepackage{amsmath}\n\\usepackage{amssymb}" :order 0.2)
(underline :snippet "\\usepackage[normalem]{ulem}" :order 0.5)
(image :snippet "\\usepackage{graphicx}" :order 2)
(svg :snippet "\\usepackage[inkscapelatex=false]{svg}" :order 2 :when image)
(longtable :snippet "\\usepackage{longtable}" :when table :order 2)
(booktabs :snippet "\\usepackage{booktabs}" :when table :order 2)
(float-wrap :snippet "\\usepackage{wrapfig}" :order 2)
(rotate :snippet "\\usepackage{rotating}" :order 2)
(caption :snippet "\\usepackage{capt-of}")
(engraved-code :when code :snippet org-latex-generate-engraved-preamble)
(!guess-pollyglossia :snippet org-latex-guess-polyglossia-language)
(!guess-babel :snippet org-latex-guess-babel-language)
(!guess-inputenc :snippet org-latex-guess-inputenc)
(!announce-end :snippet "%% end ox-latex features\n" :order 100)))
@ -1200,9 +1277,10 @@ will produce
% Define a Code environment to prettily wrap the fontified code.
\\usepackage[breakable,xparse]{tcolorbox}
\\providecommand{\\codefont}{\\footnotesize}
\\DeclareTColorBox[]{Code}{o}%
{colback=EfD!98!EFD, colframe=EfD!95!EFD,
fontupper=\\footnotesize\\setlength{\\fboxsep}{0pt},
fontupper=\\setlength{\\fboxsep}{0pt}\\codefont,
colupper=EFD,
IfNoValueTF={#1}%
{boxsep=2pt, arc=2.5pt, outer arc=2.5pt,
@ -1226,7 +1304,9 @@ as long as it:
In the default value the colors \"EFD\" and \"EfD\" are provided
as they are respectively the foreground and background colors,
just in case they aren't provided by the generated preamble, so
we can assume they are always set.
we can assume they are always set. The command \"\\codefont\" is
also provided (defaulting to \"\\footnotesize\"), to allow the
font used in \"Code\" environments to be easily tweaked.
Within this preamble there are two recognized macro-like placeholders:
@ -1323,7 +1403,19 @@ default values of which are given by `org-latex-engraved-preamble' and
(alist-get 'default
(if theme
(engrave-faces-get-theme (intern theme))
engrave-faces-current-preset-style)))))))
engrave-faces-current-preset-style))))))
(gen-theme-command
(lambda (theme)
(format "\n\\newcommand{\\engravedtheme%s}{%%\n%s\n}"
(replace-regexp-in-string
"[^A-Za-z]" "" (symbol-name theme))
(replace-regexp-in-string
"\\\\newcommand\\\\efstrut[^\n]*\n" ""
(replace-regexp-in-string
"\\\\newcommand{\\(.+?\\)}\\[1\\]" "\\\\long\\\\def\\1##1"
(replace-regexp-in-string
"#1" "##1"
(funcall gen-theme-spec theme))))))))
(when (stringp engraved-theme)
(setq engraved-theme (intern engraved-theme)))
(when (string-match "^[ \t]*\\[FVEXTRA-SETUP\\][ \t]*\n?" engraved-preamble)
@ -1353,37 +1445,57 @@ default values of which are given by `org-latex-engraved-preamble' and
t t
engraved-preamble)))
(concat
"\n% Setup for code blocks [1/2]\n\n"
"% Setup for code blocks [1/2]\n\n"
engraved-preamble
"\n\n% Setup for code blocks [2/2]: syntax highlighting colors\n\n"
(if (require 'engrave-faces-latex nil t)
(if engraved-themes
(concat
;; We don't want to re-define the efstrut, so we now need to
;; define it seperately.
(format "\\newcommand\\efstrut{%s}\n\n"
engrave-faces-latex-colorbox-strut)
;; Define default theme
(funcall gen-theme-command engraved-theme)
"\n"
;; Define other themes
(mapconcat
(lambda (theme)
(format
"\n\\newcommand{\\engravedtheme%s}{%%\n%s\n}"
(replace-regexp-in-string "[^A-Za-z]" "" (symbol-name theme))
(replace-regexp-in-string
"newcommand" "renewcommand"
(replace-regexp-in-string
"#" "##"
(funcall gen-theme-spec theme)))))
engraved-themes
gen-theme-command
(cl-remove-if (lambda (theme) (string= theme (symbol-name engraved-theme)))
engraved-themes)
"\n")
"\n\n"
(cond
((memq engraved-theme engraved-themes)
(concat "\\engravedtheme"
(replace-regexp-in-string
"[^A-Za-z]" "" engraved-theme)
"\n"))
(t (funcall gen-theme-spec engraved-theme))))
;; Load the default theme
"\n\n\\engravedtheme"
(replace-regexp-in-string
"[^A-Za-z]" "" (symbol-name engraved-theme))
"\n")
(funcall gen-theme-spec engraved-theme))
(warn "Cannot engrave source blocks. Consider installing `engrave-faces'.")
"% WARNING syntax highlighting unavailable as engrave-faces-latex was missing.\n")
"\n")))
;; Citation features
(org-export-update-features 'latex
(bibliography-csl
:condition (eq (org-cite-processor info) 'csl)
:when bibliography
:snippet org-cite-csl--generate-latex-preamble)
(bibliography-biblatex
:condition (eq (org-cite-processor info) 'biblatex)
:when bibliography
:snippet org-cite-biblatex--generate-latex-usepackage)
(bibliography-biblatex-resources
:condition (eq (org-cite-processor info) 'biblatex)
:when bibliography
:snippet org-cite-biblatex--generate-latex-bibresources
:no-precompile t
:order 90)
(bibliography-natbib
:condition (eq (org-cite-processor info) 'natbib)
:when bibliography
:snippet org-cite-natbib--generate-latex-preamble))
;;;; Compilation
(defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
@ -1627,29 +1739,29 @@ For non-floats, see `org-latex--wrap-label'."
(org-trim label)
(org-export-data main info))))))
(defun org-latex-guess-inputenc (header)
(defun org-latex-guess-inputenc (info)
"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\".
INFO is the plist used as a communication channel.
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
(let ((header (plist-get info :latex-full-header))
(cs (or (ignore-errors
(latexenc-coding-system-to-inputenc
(or org-export-coding-system buffer-file-coding-system)))
"utf8")))
(when (and cs (string-match "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}" 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))))
(plist-put info :latex-full-header
(replace-match cs t t header 1))))
nil)
(defun org-latex-guess-babel-language (header info)
(defun org-latex-guess-babel-language (info)
"Set Babel's language according to LANGUAGE keyword.
HEADER is the LaTeX header string. INFO is the plist used as
a communication channel.
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
@ -1663,52 +1775,48 @@ already loaded.
Return the new header."
(let* ((language-code (plist-get info :language))
(plist (cdr
(assoc language-code org-latex-language-alist)))
(language (plist-get plist :babel))
(language-ini-only (plist-get plist :babel-ini-only))
(plist (cdr (assoc language-code org-latex-language-alist)))
(language (plist-get plist :babel))
(header (plist-get info :latex-full-header))
(language-ini-only (plist-get plist :babel-ini-only))
(language-ini-alt (plist-get plist :babel-ini-alt))
;; If no language is set, or Babel package is not loaded, or
;; LANGUAGE keyword value is a language served by Babel
;; exclusively through ini files, return HEADER as-is.
(header (if (or language-ini-only
(not (stringp language-code))
(not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
header
(let ((options (save-match-data
(org-split-string (match-string 1 header) ",[ \t]*"))))
;; If LANGUAGE is already loaded, return header
;; without AUTO. Otherwise, replace AUTO with language or
;; append language if AUTO is not present. Languages that are
;; served in Babel exclusively through ini files are not added
;; to the babel argument, and must be loaded using
;; `\babelprovide'.
(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)))))
(babel-header-options
;; If no language is set, or Babel package is not loaded, or
;; LANGUAGE keyword value is a language served by Babel
;; exclusively through ini files, return HEADER as-is.
(and (not language-ini-only)
(stringp language-code)
(string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)
(let ((options (save-match-data
(org-split-string (match-string 1 header) ",[ \t]*"))))
(cond ((member language options) (delete "AUTO" options))
((member "AUTO" options) options)
(t (append options (list language))))))))
(when babel-header-options
;; If AUTO is present in the header options, replace it with `language'.
(setq header
(replace-match
(mapconcat (lambda (option) (if (equal "AUTO" option) language option))
babel-header-options
", ")
t nil header 1)))
;; If `\babelprovide[args]{AUTO}' is present, AUTO is
;; replaced by LANGUAGE.
(if (not (string-match "\\\\babelprovide\\[.*\\]{\\(.+\\)}" header))
header
(let ((prov (match-string 1 header)))
(if (equal "AUTO" prov)
(replace-regexp-in-string (format
"\\(\\\\babelprovide\\[.*\\]\\)\\({\\)%s}" prov)
(format "\\1\\2%s}"
(if language-ini-alt language-ini-alt
(or language language-ini-only)))
header t)
header)))))
(when (string-match "\\\\babelprovide\\[.*\\]{AUTO}" header)
(setq header
(replace-regexp-in-string
(format
"\\(\\\\babelprovide\\[.*\\]\\)\\({\\)%s}" babel-header-options)
(format "\\1\\2%s}" (if language-ini-alt language-ini-alt
(or language language-ini-only)))
header t)))
(plist-put info :latex-full-header header))
nil)
(defun org-latex-guess-polyglossia-language (header info)
(defun org-latex-guess-polyglossia-language (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.
INFO is the plist used as a communication channel.
Insertion of guessed language only happens when the Polyglossia
package has been explicitly loaded.
@ -1719,48 +1827,50 @@ replaced with the language of the document or
using \setdefaultlanguage and not as an option to the package.
Return the new header."
(let* ((language (plist-get info :language)))
(let ((header (plist-get info :latex-full-header))
(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
(when (and (stringp language)
(string-match
"\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
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* ((plist (cdr
(assoc language org-latex-language-alist)))
(polyglossia-variant (plist-get plist :polyglossia-variant))
(polyglossia-lang (plist-get plist :polyglossia))
(l (if (equal l language)
polyglossia-lang
l)))
(format (if main-language-set (format "\\setotherlanguage{%s}\n" l)
(setq main-language-set t)
"\\setmainlanguage%s{%s}\n")
(if polyglossia-variant
(format "[variant=%s]" polyglossia-variant)
"")
l)))
languages
""))
t t header 0)))))
(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))
(polyglossia-modified-header
(replace-match
(concat "\\usepackage{polyglossia}\n"
(mapconcat
(lambda (l)
(let* ((plist (cdr (assoc language org-latex-language-alist)))
(polyglossia-variant (plist-get plist :polyglossia-variant))
(polyglossia-lang (plist-get plist :polyglossia))
(l (if (equal l language)
polyglossia-lang
l)))
(format (if main-language-set (format "\\setotherlanguage{%s}\n" l)
(setq main-language-set t)
"\\setmainlanguage%s{%s}\n")
(if polyglossia-variant
(format "[variant=%s]" polyglossia-variant)
"")
l)))
languages
""))
t t header 0)))
(plist-put info :latex-full-header polyglossia-modified-header))))
nil)
(defun org-latex--remove-packages (pkg-alist info)
"Remove packages based on the current LaTeX compiler.
@ -1965,32 +2075,103 @@ 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-template
(or template
(let* ((class-options (plist-get info :latex-class-options))
(header (nth 1 (assoc class (plist-get info :latex-classes)))))
(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)
(and (not snippet?)
(plist-get info :latex-header-extra)))
""))))
info)
info)))
(class-template
(or template
(let* ((class-options (plist-get info :latex-class-options))
(header (nth 1 (assoc class (plist-get info :latex-classes)))))
(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)))
(header-split (format "\n%%--org-latex-header-temp-split-%d--\n" (random 10000)))
(header (concat (org-element-normalize-string (plist-get info :latex-header))
header-split
(and (not snippet?)
(org-element-normalize-string
(plist-get info :latex-header-extra)))))
generated-preamble preamble-nonprecompilable)
(plist-put info :latex-full-header
(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?
header)))
(if snippet?
(setq generated-preamble
(progn
(org-latex-guess-inputenc info)
(org-latex-guess-babel-language info)
(org-latex-guess-polyglossia-language info)
"\n% Generated preamble omitted for snippets."))
(let (impl-precomp impl-noprecomp)
(dolist (impl (plist-get info :feature-implementations))
(message "LaTeX feature: %s" (car impl))
(if (or impl-noprecomp (plist-get (cdr impl) :no-precompile))
(push impl impl-noprecomp)
(push impl impl-precomp)))
(message "Precomp feats: %S" (reverse (mapcar #'car impl-precomp)))
(message "No precomp feats: %S" (reverse (mapcar #'car impl-noprecomp)))
(setq generated-preamble
(string-join
(org-export-expand-feature-snippets
info (nreverse impl-precomp))
"\n\n")
preamble-nonprecompilable
(string-join
(org-export-expand-feature-snippets
info (nreverse impl-noprecomp))
"\n\n"))))
(let* ((header-parts
(split-string (plist-get info :latex-full-header)
(regexp-quote header-split)))
(header-main (car header-parts))
(header-extra (cadr header-parts))
(preamble
(concat
(org-latex--insert-compiler info)
header-main
"\n"
generated-preamble
"\n"))
(format-file
(and org-latex-precompile
;; Precompilation is disabled for xelatex/lualatex for now.
(if (member (plist-get info :latex-compiler)
'("xelatex" "lualatex"))
(progn
(display-warning
'(org latex-export disable-local-precompile)
(format "%s does not support precompilation, disabling LaTeX precompile in this buffer.\n To re-enable, run `(setq-local org-latex-precompile t)' or reopen this buffer."
(plist-get info :latex-compiler)))
(setf (buffer-local-value
'org-latex-precompile (get-buffer (plist-get info :input-buffer)))
nil))
(org-latex--precompile
info preamble
(string-match-p "\\(?:\\\\input{\\|\\\\include{\\)[^/]" preamble))))))
(when (and format-file (not snippet?))
(let ((preamble-parts (split-string preamble (regexp-quote header-split))))
(setq preamble (car preamble-parts)
preamble-nonprecompilable
(concat preamble-nonprecompilable
(cadr preamble-parts)))))
(concat (and format-file
(concat "%& " (file-name-sans-extension format-file) "\n"))
(and (plist-get info :time-stamp-file)
(format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
preamble
(and format-file
"\n% end precompiled preamble\n\\ifcsname endofdump\\endcsname\\endofdump\\fi\n")
"\n"
preamble-nonprecompilable
(and preamble-nonprecompilable
(not (string-empty-p preamble-nonprecompilable))
"\n")
header-extra))))
(defun org-latex-template (contents info)
"Return complete document string after LaTeX conversion.
@ -1999,12 +2180,7 @@ holding export options."
(let ((title (org-export-data (plist-get info :title) info))
(spec (org-latex--format-spec info)))
(concat
;; Timestamp.
(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.
;; Timestamp, compiler statement, document class and packages.
(org-latex-make-preamble info)
;; Possibly limit depth for headline numbering.
(let ((sec-num (plist-get info :section-numbers)))
@ -2041,12 +2217,6 @@ holding export options."
(let ((template (plist-get info :latex-hyperref-template)))
(and (stringp template)
(format-spec template spec)))
;; engrave-faces-latex preamble
(when (and (eq (plist-get info :latex-src-block-backend) 'engraved)
(org-element-map (plist-get info :parse-tree)
'(src-block inline-src-block) #'identity
info t))
(org-latex-generate-engraved-preamble info))
;; Document start.
"\\begin{document}\n\n"
;; Title command.
@ -2074,6 +2244,118 @@ holding export options."
;; Document end.
"\\end{document}")))
(defvar org-latex-precompile t
"Precompile the preamble during export.
This requires the LaTeX package \"mylatexformat\" to be installed.")
(defconst org-latex--precompile-log "*Org LaTeX Precompilation*")
(defvar org-latex-precompile-command
"%l -output-directory %o -ini -jobname=%b \"&%L\" mylatexformat.ltx %f")
(defvar org-latex-precompile-compiler-map
'(("pdflatex" . "latex")
("xelatex" . "xelatex -no-pdf")
("lualatex" . "dvilualatex")))
(defun org-latex--precompile (info preamble &optional tempfile-p)
"Precompile/dump LaTeX PREAMBLE text.
The path to the format file (.fmt) is returned. If the format
file could not be found in the persist cache, it is generated
according to PROCESSING-INFO and stored. INFO is a plist used as
a communication channel.
If TEMPFILE-P is non-nil, then it is assumed the preamble does
not contain any relative references to other files.
This is intended to speed up Org's LaTeX preview generation
process."
(let ((preamble-hash
(thread-first
preamble
(concat
(plist-get info :latex-compiler)
(if tempfile-p "-temp"
default-directory))
(sha1)))
(default-directory
(if tempfile-p temporary-file-directory default-directory)))
(or (cadr
(org-persist-read "LaTeX format file cache"
(list :key preamble-hash)
nil nil :read-related t))
(when-let ((dump-file
(org-latex--precompile-preamble
info preamble (expand-file-name preamble-hash temporary-file-directory))))
(cadr
(org-persist-register `(,"LaTeX format file cache"
(file ,dump-file))
(list :key preamble-hash)
:write-immediately t))))))
(defun org-latex--remove-cached-preamble (latex-compiler preamble &optional tempfile-p)
"Remove the cached preamble file for PREAMBLE compiled with LATEX-COMPILER.
TEMPFILE-P should be set to mirror the caching `org-latex--precompile' call
which is intended to be evicted from the cache."
(let ((preamble-hash
(thread-first
preamble
(concat
latex-compiler
(if tempfile-p "-temp"
default-directory))
(sha1))))
(org-persist-unregister "LaTeX format file cache"
(list :key preamble-hash)
:remove-related t)))
(defun org-latex--precompile-preamble (info preamble basepath)
"Precompile PREAMBLE with \"mylatexformat\".
The PREAMBLE string is placed in BASEPATH.tex and compiled
according to PROCESSING-INFO. If compilation and dumping
succeeded, BASEPATH.fmt will be returned.
Should any errors occur during compilation, nil will be returned,
and appropriate warnings may be emitted."
(let ((dump-file (concat basepath ".fmt"))
(preamble-file (concat basepath ".tex"))
(precompile-buffer
(with-current-buffer
(get-buffer-create org-latex--precompile-log)
(erase-buffer)
(current-buffer))))
(with-temp-file preamble-file
(insert preamble "\n\\endofdump\n"))
(message "Precompiling Org LaTeX preamble...")
(condition-case nil
(org-compile-file
preamble-file (list org-latex-precompile-command)
"fmt" nil precompile-buffer
(or (plist-get info :precompile-format-spec)
`((?l . ,(plist-get info :latex-compiler))
(?L . ,(plist-get info :latex-compiler)))))
(:success
(kill-buffer precompile-buffer)
(delete-file preamble-file)
dump-file)
(error
(unless (= 0 (call-process "kpsewhich" nil nil nil "mylatexformat.ltx"))
(display-warning
'(org latex-preview preamble-precompilation)
"The LaTeX package \"mylatexformat\" is required for precompilation, but could not be found")
:warning)
(unless (= 0 (call-process "kpsewhich" nil nil nil "preview.sty"))
(display-warning
'(org latex-preview preamble-precompilation)
"The LaTeX package \"preview\" is required for precompilation, but could not be found")
:warning)
(display-warning
'(org latex-preview preamble-precompilation)
(format "Failed to precompile preamble (%s), see the \"%s\" buffer."
preamble-file precompile-buffer)
:warning)
nil))))
;;; Transcode Functions
@ -2478,8 +2760,12 @@ INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
(defun org-latex-inline-src-block--engraved (info code lang)
"Transcode an inline src block's content from Org to LaTeX, using engrave-faces.
INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
(org-latex-src--engrave-code
code lang nil (plist-get info :latex-engraved-options) t))
(let ((engraved-theme (plist-get info :latex-engraved-theme)))
(when (stringp engraved-theme)
(setq engraved-theme (intern engraved-theme)))
(org-latex-src--engrave-code
code lang engraved-theme nil
(plist-get info :latex-engraved-options) t)))
(defun org-latex-inline-src-block--listings (info code lang)
"Transcode an inline src block's content from Org to LaTeX, using lstlistings.
@ -2943,12 +3229,10 @@ INFO is a plist holding contextual information. See
link (plist-get info :latex-inline-image-rules)))
(path (org-latex--protect-text
(pcase type
((or "http" "https" "ftp" "mailto" "doi")
(concat type ":" raw-path))
("file"
(org-export-file-uri raw-path))
(_
raw-path)))))
(concat type ":" raw-path))))))
(cond
;; Link type is handled by a special function.
((org-export-custom-protocol-maybe link desc 'latex info))
@ -3532,7 +3816,7 @@ and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
(when (eq mathescape 'yes)
(or engrave-faces-latex-mathescape t)))))
(defun org-latex-src--engrave-code (content lang &optional theme options inline)
(defun org-latex-src--engrave-code (content lang &optional theme explicit-theme-p options inline)
"Engrave CONTENT to LaTeX in a LANG-mode buffer, and give the result.
When the THEME symbol is non-nil, that theme will be used.
@ -3573,12 +3857,12 @@ to the Verbatim environment or Verb command."
(concat "\\begin{Code}\n\\begin{Verbatim}" engraved-options "\n"
engraved-code "\n\\end{Verbatim}\n\\end{Code}"))))
(kill-buffer engraved-buffer)
(if theme
(concat "{\\engravedtheme"
(if (and theme explicit-theme-p)
(concat "\\begingroup\\engravedtheme"
(replace-regexp-in-string "[^A-Za-z]" ""
(symbol-name theme))
engraved-wrapped
"}")
"\\endgroup")
engraved-wrapped))
(user-error "Cannot engrave code as `engrave-faces-latex' is unavailable.")))
@ -3612,7 +3896,16 @@ and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
`(("linenos")
("firstnumber" ,(number-to-string (1+ num-start)))))
(and local-options `((,local-options))))))
(engraved-theme (plist-get attributes :engraved-theme))
(intern-safe
(lambda (name)
(if (stringp name)
(intern name)
name)))
(engraved-doc-theme
(funcall intern-safe (plist-get info :latex-engraved-theme)))
(engraved-theme
(or (funcall intern-safe (plist-get attributes :engraved-theme))
engraved-doc-theme))
(content
(let* ((code-info (org-export-unravel-code src-block))
(max-width
@ -3638,7 +3931,8 @@ and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
(org-latex-src--engrave-mathescape-p info options)))
(org-latex-src--engrave-code
content lang
(when engraved-theme (intern engraved-theme))
engraved-theme
(not (eq engraved-theme engraved-doc-theme))
options))))
(concat (car float-env) body (cdr float-env))))
@ -4352,13 +4646,21 @@ Return PDF file's name."
async subtreep visible-only body-only ext-plist
#'org-latex-compile)))
(defun org-latex-compile (texfile &optional snippet)
(defun org-latex-export-to-pdf-and-open (&optional async subtreep visible-only body-only ext-plist)
(let ((outfile (org-export-output-file-name ".tex" subtreep)))
(org-export-to-file 'latex outfile
async subtreep visible-only body-only ext-plist
(lambda (f) (org-latex-compile f nil t)))))
(defun org-latex-compile (texfile &optional snippet open-pdf)
"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.
buffer. When the process is a shell command (and not a
function), it will be run asyncronously via `org-async-call',
unless the current session is `noninteractive'.
When optional argument SNIPPET is non-nil, TEXFILE is a temporary
file used to preview a LaTeX snippet. In this case, do not
@ -4393,16 +4695,34 @@ produced."
(?L . ,(shell-quote-argument compiler))))
(log-buf-name "*Org PDF LaTeX Output*")
(log-buf (and (not snippet) (get-buffer-create log-buf-name)))
outfile)
;; Erase compile buffer at the start.
(outfile (expand-file-name (concat (file-name-base texfile) ".pdf")
(file-name-directory texfile))))
(with-current-buffer log-buf
(erase-buffer))
(setq outfile
(org-compile-file
texfile process "pdf"
(format "See %S for details" log-buf-name)
log-buf spec))
(org-latex-compile--postprocess outfile log-buf snippet)
(if (or noninteractive (functionp process))
(progn
(org-compile-file texfile process "pdf"
(format "See %S for details" log-buf-name)
log-buf spec)
(and open-pdf (org-open-file outfile))
(org-latex-compile--postprocess outfile log-buf snippet))
(let ((failure-msg (format "File %S wasn't produced (exit code %%d). See %%s for details."
outfile))
async-call-spec)
(dolist (cmd (reverse (org-compile-file-commands
texfile process "pdf" spec)))
(setq async-call-spec
(list cmd
:buffer log-buf
:success
(or async-call-spec
(list (and open-pdf (lambda (_ _ _) (org-open-file outfile)))
(lambda (_ buf _)
(org-latex-compile--postprocess outfile buf snippet))))
:failure
failure-msg)))
(message "Compiling %s..." texfile)
(apply #'org-async-call async-call-spec)))
;; Return output file name.
outfile))

View File

@ -615,10 +615,8 @@ INFO is a plist holding contextual information. See
;; Ensure DESC really exists, or set it to nil.
(desc (and (not (string= desc "")) desc))
(path (pcase type
((or "http" "https" "ftp" "mailto")
(concat type ":" raw-path))
("file" (org-export-file-uri raw-path))
(_ raw-path))))
(_ (concat type ":" raw-path)))))
(cond
;; Link type is handled by a special function.
((org-export-custom-protocol-maybe link desc 'man info))

157
lisp/ox-mathml.el Normal file
View File

@ -0,0 +1,157 @@
;;; ox-mathml.el --- Support for MathML exports -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2023 TEC
;;
;; Author: TEC <contact@tecosaur.net>
;; Maintainer: TEC <contact@tecosaur.net>
;; Created: February 27, 2023
;; Modified: February 27, 2023
;; Version: 0.0.1
;; Keywords: abbrev bib c calendar comm convenience data docs emulations extensions faces files frames games hardware help hypermedia i18n internal languages lisp local maint mail matching mouse multimedia news outlines processes terminals tex tools unix vc wp
;; Homepage: https://github.com/tecosaur/ox-mathml
;; Package-Requires: ((emacs "24.3"))
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Support for MathML exports
;;
;;; Code:
(defgroup org-mathml nil
"Options for generation of MathML representations of LaTeX math."
:tag "Org MathML export"
:group 'org-export)
(defcustom org-mathml-converter-jar-file nil
"Value of\"%j\" in `org-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-mathml
:version "24.1"
:type '(choice
(const :tag "None" nil)
(file :tag "JAR file" :must-match t)))
(defcustom org-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: Shell-escaped LaTeX fragment to be converted.
It must not be used inside a quoted argument, the result of %i
expansion inside a quoted argument is undefined.
%o: Output MathML file.
This command is used by `org-mathml-convert-latex'.
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 --preload=amsmath.sty --preload=amssymb.sty --presentationmathml=%o\"."
:group 'org-mathml
:version "24.1"
:type '(choice
(const :tag "None" nil)
(string :tag "\nShell command")))
(defun org-mathml-converter-available-p ()
"Return t if `org-mathml-convert-command' is usable."
(save-match-data
(when (and (boundp 'org-mathml-convert-command)
org-mathml-convert-command)
(let ((executable (car (split-string
org-mathml-convert-command))))
(when (executable-find executable)
(if (string-match
"%j" org-mathml-convert-command)
(file-readable-p org-mathml-converter-jar-file)
t))))))
(defun org-mathml-convert-latex (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
successful, 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-mathml-convert-command
`((?j . ,(and org-mathml-converter-jar-file
(shell-quote-argument
(expand-file-name
org-mathml-converter-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-mathml-converter-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)))
((warn "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-mathml-convert-latex-cached (latex-frag)
"Use `org-mathml-convert-latex' but check local cache first."
(let ((latex-hash-path
(expand-file-name
(concat
"org-mathml-formula-"
(sha1
(prin1-to-string
(list latex-frag
org-mathml-convert-command)))
".mathml")
temporary-file-directory))
print-length print-level)
(unless (file-exists-p latex-hash-path)
(org-mathml-convert-latex latex-frag latex-hash-path))
(and (file-exists-p latex-hash-path)
latex-hash-path)))
(provide 'ox-mathml)
;;; ox-mathml.el ends here

View File

@ -544,11 +544,9 @@ INFO is a plist holding contextual information. See
(type (org-element-property :type link))
(raw-path (org-element-property :path link))
(path (cond
((member type '("http" "https" "ftp" "mailto"))
(concat type ":" raw-path))
((string-equal type "file")
(org-export-file-uri (funcall link-org-files-as-md raw-path)))
(t raw-path))))
(t (concat type ":" raw-path)))))
(cond
;; Link type is handled by a special function.
((org-export-custom-protocol-maybe link desc 'md info))

View File

@ -34,6 +34,7 @@
(require 'org-macs)
(require 'ox)
(require 'table nil 'noerror)
(require 'ox-mathml)
(declare-function org-at-heading-p "org" (&optional _))
(declare-function org-back-to-heading "org" (&optional invisible-ok))
@ -2246,11 +2247,9 @@ used as a communication channel."
(cl-assert (org-element-type-p 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)
(cond ((file-name-absolute-p raw-path)
(expand-file-name raw-path))
(t raw-path))))
(t (concat type ":" raw-path)))))
(src-expanded (if (file-name-absolute-p src) src
(expand-file-name src (file-name-directory
(plist-get info :input-file)))))
@ -3712,114 +3711,147 @@ contextual information."
(defun org-odt--translate-latex-fragments (tree _backend info)
(let ((processing-type (plist-get info :with-latex))
(count 0)
(count 0)
(warning nil))
;; 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)
(setq warning "`org-odt-with-latex': LaTeX to MathML converter not available. Falling back to verbatim.")
(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))
(setq warning "`org-odt-with-latex': LaTeX to PNG converter not available. Falling back to verbatim.")
(setq processing-type 'verbatim)))
(otherwise
(setq warning "`org-odt-with-latex': Unknown LaTeX option. Forcing verbatim.")
(setq processing-type 'verbatim)))
;; Display warning if the selected PROCESSING-TYPE is not
;; available, but there are fragments to be converted.
(when warning
(org-element-map tree '(latex-fragment latex-environment)
(lambda (_) (warn warning))
info 'first-match nil t))
;; 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)
org-preview-latex-image-directory)
(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.
(link
(with-temp-buffer
(insert latex-frag)
(delay-mode-hooks (let ((org-inhibit-startup t)) (org-mode)))
;; When converting to a PNG image, make sure to
;; copy all LaTeX header specifications from the
;; Org source.
(unless (eq processing-type 'mathml)
(let ((h (plist-get info :latex-header)))
(when h
(insert "\n"
(replace-regexp-in-string
"^" "#+LATEX_HEADER: " h)))))
(org-format-latex cache-subdir nil nil cache-dir
nil display-msg nil
processing-type)
(goto-char (point-min))
(skip-chars-forward " \t\n")
(org-element-link-parser))))
(if (not (org-element-type-p link 'link))
(message "LaTeX Conversion failed.")
;; Conversion succeeded. Parse above Org-style link to
;; a `link' object.
(let ((replacement
(cl-case (org-element-type latex-*)
;;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
(list 'paragraph
(list :style "OrgFormula"
:name
(org-element-property :name latex-*)
:caption
(org-element-property :caption latex-*)))
link))
;; 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 latex-* replacement)))))
info nil nil t)))
;; MathML will be handled seperately.
(if (and (memq processing-type '(t mathml))
(fboundp 'org-format-latex-mathml-available-p)
(org-format-latex-mathml-available-p)
(plist-put info :with-latex 'mathml))
(org-element-map tree '(latex-fragment latex-environment)
(lambda (latex)
(cl-incf count)
(if-let ((latex-frag (org-element-property :value latex))
(path (org-mathml-convert-latex-cached latex-frag))
(link (list 'link
(list :type "file"
:path path
:format 'bracket
:raw-link (format "file:%s" path))))
(replacement
(if (eq (org-element-type latex) 'latex-environment)
;;LaTeX environment. Mimic a "standalone image
;; or formula" by enclosing the `link' in
;; a `paragraph'. Copy over original
;; attributes, captions to the enclosing
;; paragraph.
(org-element-adopt-elements
(list 'paragraph
(list :style "OrgFormula"
:name
(org-element-property :name latex)
:caption
(org-element-property :caption latex)))
link)
link)))
(progn
;; 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))
(setq warning "Conversion of LaTeX to MathML failed. Falling back to verbatim.")))
info nil nil)
;; Normalize processing-type to one of dvipng or verbatim.
;; If the desired converter is not available, force verbatim
;; processing.
(cl-case processing-type
((t mathml)
(setq warning "LaTeX to MathML converter not available. Falling back to verbatim."
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))
(setq warning "LaTeX to PNG converter not available. Falling back to verbatim."
processing-type 'verbatim)))
(otherwise
(setq warning "Unknown LaTeX option. Forcing verbatim."
processing-type 'verbatim)))
;; Display warning if the selected PROCESSING-TYPE is not
;; available, but there are fragments to be converted.
(when warning
(org-element-map tree '(latex-fragment latex-environment)
(lambda (_) (warn warning))
info 'first-match nil t))
;; 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 '(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)
org-preview-latex-image-directory))
(file-name-sans-extension
(file-name-nondirectory input-file))))
(display-msg
(cl-case processing-type
((dvipng imagemagick)
(format "Creating LaTeX Image %d..." count))))
;; Get an Org-style link to PNG image.
(link
(with-temp-buffer
(insert latex-frag)
(delay-mode-hooks (let ((org-inhibit-startup t)) (org-mode)))
;; When converting to a PNG image, make sure to
;; copy all LaTeX header specifications from the
;; Org source.
(let ((h (plist-get info :latex-header)))
(when h
(insert "\n"
(replace-regexp-in-string
"^" "#+LATEX_HEADER: " h))))
(org-latex-preview-replace-fragments
cache-subdir processing-type cache-dir display-msg)
(goto-char (point-min))
(skip-chars-forward " \t\n")
(org-element-link-parser))))
(if (not (eq 'link (org-element-type link)))
(message "LaTeX Conversion failed.")
;; Conversion succeeded. Parse above Org-style link to
;; a `link' object.
(let ((replacement
(cl-case (org-element-type latex-*)
;;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))
;; 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)
@ -4146,7 +4178,7 @@ MathML source to kill ring depending on the value of
(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)))
(let ((mathml (org-mathml-convert-latex-cached latex-frag)))
(unless mathml (error "No Math formula created"))
(insert mathml)
;; Add MathML to kill ring, if needed.

View File

@ -345,10 +345,8 @@ Return output file name."
(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-with-file-buffer filename
(font-lock-ensure)
(org-fold-show-all)
(setq newbuf (htmlize-buffer)))
@ -363,8 +361,7 @@ Return output file name."
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)))))
(kill-buffer newbuf))))
(provide 'ox-org)

View File

@ -565,30 +565,25 @@ 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)))))
(let* ((org-inhibit-startup t))
(org-with-file-buffer filename
(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)))))))))
(defun org-publish-attachment (_plist filename pub-dir)
"Publish a file with no transformation of any kind.
@ -852,17 +847,13 @@ Return value may be a string or a list, depending on the type of
PROPERTY, i.e. \"behavior\" parameter from `org-export-options-alist'."
(let ((file (org-publish--expand-file-name file project)))
(when (and (file-readable-p file) (not (directory-name-p file)))
(let* ((org-inhibit-startup t)
(visiting (find-buffer-visiting file))
(buffer (or visiting (find-file-noselect file))))
(unwind-protect
(plist-get (with-current-buffer buffer
(if (not visiting) (org-export-get-environment backend)
;; Protect local variables in open buffers.
(org-export-with-buffer-copy
(org-export-get-environment backend))))
property)
(unless visiting (kill-buffer buffer)))))))
(let* ((org-inhibit-startup t))
(plist-get (org-with-file-buffer file
(if (not org-file-buffer-created) (org-export-get-environment backend)
;; Protect local variables in open buffers.
(org-export-with-buffer-copy
(org-export-get-environment backend))))
property)))))
(defun org-publish-find-title (file project)
"Find the title of FILE in PROJECT."

View File

@ -110,7 +110,8 @@
(: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-dirtitle "TEXINFO_DIR_TITLE" nil nil t) ;Obsolete.
(:texinfo-dirname "TEXINFO_DIR_NAME" nil nil t)
(:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)
(:texinfo-printed-title "TEXINFO_PRINTED_TITLE" nil nil t)
;; Other variables.
@ -147,12 +148,10 @@
"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
@ -205,7 +204,6 @@ 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."
:group 'org-export-texinfo
:version "27.1"
:package-version '(Org . "9.2")
:type '(repeat
@ -233,7 +231,6 @@ 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"))
@ -244,38 +241,32 @@ The function result will be used in the section format string."
"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 nil
@ -285,7 +276,6 @@ 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)))
@ -297,7 +287,6 @@ This should an indicating command, e.g., \"@code\", \"@kbd\" or
\"@samp\".
It can be overridden locally using the \":indic\" attribute."
:group 'org-export-texinfo
:type 'string
:version "26.1"
:package-version '(Org . "9.1")
@ -323,7 +312,6 @@ to typeset and protects special characters.
When no association is found for a given markup, text is returned
as-is."
:group 'org-export-texinfo
:version "26.1"
:package-version '(Org . "9.1")
:type 'alist
@ -341,7 +329,6 @@ The function must accept two parameters:
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)
@ -361,7 +348,6 @@ The function must accept six parameters:
CONTENTS the contents of the inlinetask, as a string.
The function should return the string to be exported."
:group 'org-export-texinfo
:type 'function)
;;;; LaTeX
@ -374,7 +360,6 @@ fragments as Texinfo \"@displaymath\" and \"@math\" commands
respectively. Alternatively, when set to `detect', the exporter
does so only if the installed version of Texinfo supports the
necessary commands."
:group 'org-export-texinfo
:package-version '(Org . "9.6")
:type '(choice
(const :tag "Detect" detect)
@ -391,7 +376,6 @@ body but is followed by another item, then the second item is
transcoded to `@itemx'. See info node `(org)Plain lists in
Texinfo export' for how to enable this for individual lists."
:package-version '(Org . "9.6")
:group 'org-export-texinfo
:type 'boolean
:safe t)
@ -406,7 +390,6 @@ 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
:version "26.1"
:package-version '(Org . "9.1")
:type '(repeat :tag "Shell command sequence"
@ -417,7 +400,6 @@ the output file."
"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
@ -815,25 +797,49 @@ holding export options."
(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")))
(let* ((dircat (or (plist-get info :texinfo-dircat) "Misc"))
(file (or (org-strip-quotes (plist-get info :texinfo-filename))
(plist-get info :output-file)))
(file (if file (file-name-sans-extension file)))
(dn (or (plist-get info :texinfo-dirname)
(plist-get info :texinfo-dirtitle))) ;Obsolete name.
;; Strip any terminating `.' from `dn'.
(dn (if (and dn (string-match "\\.\\'" dn)) (substring dn 0 -1) dn))
;; The direntry we need to produce has the shape:
;; * DIRNAME: NODE. DESCRIPTION.
;; where NODE is usually just `(FILENAME)', and where
;; `* FILENAME.' is a shorthand for `* FILENAME: (FILENAME).'
(dirname
(cond
((and dn (string-match
(eval-when-compile
(concat "\\`\\(?:"
"\\* \\(?1:.*\\)" ;Starts with `* ' or
"\\|\\(?1:.*(.*).*\\)" ;contains parens.
"\\)\\'"))
dn))
;; When users provide a `dn' that looks like a complete
;; `* DIRNAME: (FILENAME).' thingy, we just trust them to
;; provide something valid (just making sure it starts
;; with `* ' and ends with `.').
(format "* %s." (match-string 1 dn)))
;; `dn' is presumed to be just the DIRNAME part, so generate
;; either `* DIRNAME: (FILENAME).' or `* FILENAME.', whichever
;; is shortest.
((and dn (not (equal dn file)))
(format "* %s: (%s)." dn (or file dn)))
(t (format "* %s." file)))))
(concat "@dircategory " dircat "\n"
"@direntry\n"
(let ((dirdesc
(let ((desc (or (plist-get info :texinfo-dirdesc)
title)))
(cond ((not desc) nil)
((string-suffix-p "." desc) desc)
(t (concat desc "."))))))
(if dirdesc (format "%-23s %s" dirname dirdesc) dirname))
"\n"
"@end direntry\n\n"))
;; Title
"@finalout\n"
"@titlepage\n"
@ -1320,11 +1326,9 @@ INFO is a plist holding contextual information. See
(desc (and (not (string= desc "")) desc))
(path (org-texinfo--sanitize-content
(cond
((member type '("http" "https" "ftp"))
(concat type ":" raw-path))
((string-equal type "file")
(org-export-file-uri raw-path))
(t raw-path)))))
(t (concat type ":" raw-path))))))
(cond
((org-export-custom-protocol-maybe link desc 'texinfo info))
((org-export-inline-image-p link org-texinfo-inline-image-rules)
@ -1591,7 +1595,7 @@ information."
(concat
"@noindent"
(mapconcat
'identity
#'identity
(delq nil
(list
(let ((closed (org-element-property :closed planning)))

View File

@ -1060,7 +1060,7 @@ mode."
(cl-defstruct (org-export-backend (:constructor org-export-create-backend)
(:copier nil))
name parent transcoders options filters blocks menu)
name parent transcoders options filters blocks menu feature-conditions feature-implementations)
;;;###autoload
(defun org-export-get-backend (name)
@ -1166,6 +1166,62 @@ returns filters inherited from parent backends, if any."
(setq filters (append filters (org-export-backend-filters backend))))
filters)))
(defvar org-export-conditional-features)
(defun org-export-get-all-feature-conditions (backend)
"Return full feature condition alist 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 feature conditions, and values are feature symbols.
Unlike `org-export-backend-feature-conditions', this function
also returns conditions inherited from parent back-ends, if any."
(when (symbolp backend) (setq backend (org-export-get-backend backend)))
(and backend
(let ((conditions (org-export-backend-feature-conditions backend))
parent)
(while (setq parent (org-export-backend-parent backend))
(setq backend (org-export-get-backend parent))
(dolist (condition (org-export-backend-feature-conditions backend))
(push condition conditions)))
(dolist (condition org-export-conditional-features)
(unless (assq (car condition) conditions)
(push condition conditions)))
conditions)))
(defun org-export-get-all-feature-implementations (backend)
"Return full feature implementation alist 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 feature symbols, and values are an implementation
specification plist.
Unlike `org-export-backend-feature-implementations', this function
also returns implementations inherited from parent back-ends, if any."
(when (symbolp backend) (setq backend (org-export-get-backend backend)))
(and backend
(let ((implementations (org-export-backend-feature-implementations backend))
parent)
(while (setq parent (org-export-backend-parent backend))
(setq backend (org-export-get-backend parent))
(dolist (implementation (org-export-backend-feature-implementations backend))
(unless (assq (car implementation) implementations)
(push implementation implementations))))
implementations)))
(defun org-export-install-features (info)
"Install feature conditions and implementations in the communication channel.
INFO is a plist containing the current communication channel.
Return the updated communication channel."
(plist-put info :feature-conditions
(org-export-get-all-feature-conditions
(plist-get info :back-end)))
(plist-put info :feature-implementations
(org-export-get-all-feature-implementations
(plist-get info :back-end))))
(defun org-export-define-backend (backend transcoders &rest body)
"Define a new backend BACKEND.
@ -1277,20 +1333,24 @@ keywords are understood:
`org-export-options-alist' for more information about
structure of the values."
(declare (indent 1))
(let (filters menu-entry options)
(let (filters menu-entry options feature-conditions feature-implementations)
(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)))
(:feature-conditions-alist (setq feature-conditions (pop body)))
(:feature-implementations-alist (setq feature-implementations (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))))
:menu menu-entry
:feature-conditions feature-conditions
:feature-implementations feature-implementations))))
(defun org-export-define-derived-backend (child parent &rest body)
"Create a new backend as a variant of an existing one.
@ -1337,7 +1397,7 @@ The backend 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)
(let (filters menu-entry options transcoders feature-conditions feature-implementations)
(while (keywordp (car body))
(let ((keyword (pop body)))
(pcase keyword
@ -1345,6 +1405,8 @@ The backend could then be called with, for example:
(:menu-entry (setq menu-entry (pop body)))
(:options-alist (setq options (pop body)))
(:translate-alist (setq transcoders (pop body)))
(:feature-conditions-alist (setq feature-conditions (pop body)))
(:feature-implementations-alist (setq feature-implementations (pop body)))
(_ (error "Unknown keyword: %s" keyword)))))
(org-export-register-backend
(org-export-create-backend :name child
@ -1352,7 +1414,9 @@ The backend could then be called with, for example:
:transcoders transcoders
:options options
:filters filters
:menu menu-entry))))
:menu menu-entry
:feature-conditions feature-conditions
:feature-implementations feature-implementations))))
@ -2055,6 +2119,550 @@ keywords before output."
(funcall (intern (format "org-element-%s-interpreter" type))
blob contents))))
;;; Conditional/Generated Features
;;
;; Many formats have some version of a preamble, whether it be HTML's
;; <head>...</head> or the content before LaTeX's \begin{document}.
;; Depending on the particular features in the Org document being
;; exported, different setup snippets will be needed. There's the
;; "everything and the kitchen sink" approach of adding absolutely
;; everything that might be needed, and the post-translation editing
;; with filters approach, but neither really solve this problem nicely.
;;
;; The conditional/generated preamble defines mechanisms of detecting
;; which "export features" are used in a document, handles
;; interactions between features, and provides/generates content to
;; support the features.
;;
;; Each export feature condition takes the form of a
;; (CONDITION . FEATURES) cons cell (see `org-export-detect-features'),
;; and each implementation takes the form of a (FEATURE . (:KEY VALUE ...))
;; associated plist (see `org-export-resolve-feature-implementations'
;; and `org-export-expand-feature-snippets').
;;
;; This functionality is applied during export as follows:
;; 1. The export feature conditions and implementations are installed
;; into the INFO plist with `org-export-install-features'.
;; This simply applies `org-export-get-all-feature-conditions' and
;; `org-export-get-all-feature-implementations', which merges the
;; backend's conditions/implementations with all of it's parents and
;; finally the global condition list
;; `org-export-conditional-features'.
;; 2. The "export features" used in a document are detected with
;; `org-export-detect-features'.
;; 3. The interaction between different feature implementations is
;; resolved with `org-export-resolve-feature-implementations',
;; producing an ordered list of implementations to be actually used
;; in an export.
;; 4. The feature implementation's snippets are transformed into strings
;; to be inserted with `org-export-expand-feature-snippets'.
(defcustom org-export-conditional-features
`(("^[ \t]*#\\+print_bibliography:" bibliography)
(,(lambda (info)
(org-element-map (plist-get info :parse-tree)
'link
(lambda (link)
(and (member (org-element-property :type link)
'("http" "https" "ftp" "file"))
(file-name-extension (org-element-property :path link))
(member (downcase (file-name-extension
(org-element-property :path link)))
image-file-name-extensions)))
info t))
image)
(,(lambda (info)
(org-element-map (plist-get info :parse-tree)
'table #'identity info t))
table)
(,(lambda (info)
(org-element-map (plist-get info :parse-tree)
'(src-block inline-src-block) #'identity info t))
code))
"Org feature tests and associated feature flags.
Alist where the car is a test for the presense of the feature,
and the CDR is either a single feature symbol or a list of
feature symbols.
See `org-export-detect-features' for how this is processed."
:group 'org-export-general
:type '(alist :key-type
(choice (regexp :tag "Feature test regexp")
(variable :tag "Feature variable")
(function :tag "Feature test function"))
:value-type
(repeat symbol :tag "Feature symbols")))
(defun org-export-detect-features (info)
"Detect features from `org-export-conditional-features' in INFO.
More specifically, for each (CONDITION . FEATURES) cons cell of
the :feature-conditions list in INFO, the CONDITION is evaluated
in two phases.
In phase one, CONDITION is transformed like so:
- If a variable symbol, the value is fetched
- If a function symbol, the function is called with INFO as the
sole argument
- If a string, passed on unmodified
In phase two, if the CONDITION result is a string, it is used as
a case-sensitive regexp search in the buffer. The regexp
matching is taken as confirmation of the existance of FEATURES.
Any other non-nil value indicates the existance of FEATURES.
A list of all detected feature symbols is returned.
This function should be run in the processed export Org buffer,
after includes have been expanded and commented trees removed."
(delete-dups
(cl-loop
for (condition . features) in (plist-get info :feature-conditions)
for matcher =
(cond
((stringp condition) condition)
((functionp condition) (funcall condition info))
((symbolp condition) (symbol-value condition))
(t (error "org-export: Feature condition %s (for %s) unable to be used"
condition features)))
for active-features =
(and (if (stringp matcher)
(save-excursion
(goto-char (point-min))
(re-search-forward matcher nil t))
matcher)
(copy-sequence features))
when active-features
nconc active-features)))
(define-error 'org-missing-feature-dependency
"A feature was asked for, but is not availible")
(define-error 'org-circular-feature-dependency
"There was a circular dependency between some features")
(defun org-export-resolve-feature-implementations (info &optional features implementations)
"Resolve the IMPLEMENTATIONS of FEATURES, of INFO.
FEATURES should be a list of all feature symbols to be resolved,
and defaults to (plist-get info :features). IMPLEMENTATIONS
should be an alist of feature symbols and specification plists,
and defaults to (plist-get info :feature-implementations).
The following keys of the each implementation plist are recognised:
- :snippet, which is either,
- A string, which should be included in the preamble verbatim.
- A variable, the value of which should be included in the preamble.
- A function, which is called with two arguments the export info,
and the list of feature flags. The returned value is included in
the preamble.
- :requires, a feature or list of features this feature will enable.
- :when, a feature or list of features which are required for this
feature to be active.
- :prevents, a feature or list of features that should be masked.
- :order, for when inclusion order matters. Feature implementations
with a lower order appear first. The default is 0.
- :after, a feature or list of features that must be preceding.
- :before, a feature or list of features that must be succeeding.
This function processes :requires, :when, and :prevents in turn,
sorting according by :order both before processing :requires and
after processing :prevents. The final implementation list is
returned."
(let* ((explicit-features (or features (plist-get info :features)))
(implementations (or implementations
(plist-get info :feature-implementations)))
(current-implementations
(sort (cl-loop for feat in explicit-features
collect (assq feat implementations))
(lambda (a b)
(< (or (plist-get (cdr a) :order) 0)
(or (plist-get (cdr b) :order) 0)))))
;; require-records serves to record /why/ a particular implementation
;; is used. It takes the form of an alist with feature symbols as the
;; keys, and a list of features that ask for that feature as values.
;; A t value is used to indicate the feature has been explicitly
;; required.
(require-records
(cl-loop for feat in explicit-features
collect (list feat t))))
;; * Process ~:requires~
;; Here we temporarily treat current-implementations as a queue of
;; unproceesed implementations, and for each implemention move
;; it to processed-implementations if not already present.
;; :requires are processed by being added to the current-implementations
;; stack as they are seen. Along the way require-records is built for
;; the sake of the subsequent :prevents processing.
(let ((impl-queue-last (last current-implementations))
processed-implementations impl)
(while current-implementations
(setq impl (pop current-implementations))
(unless (memq impl processed-implementations)
(push impl processed-implementations)
(dolist (req (org-ensure-list
(plist-get (cdar processed-implementations) :requires)))
(unless (assq req processed-implementations)
(let ((required-impl (assq req implementations)))
(unless required-impl
(signal 'org-missing-feature-dependency
(format "The feature `%s' was asked for but could not be found"
req)))
(setq impl-queue-last
(if current-implementations
(setcdr impl-queue-last (list required-impl))
(setq current-implementations (list required-impl))))
(push (car impl) (alist-get req require-records)))))))
(setq current-implementations
(nreverse (delq nil processed-implementations))))
;; * Process ~:when~
;; More specifically, remove features with unfulfilled :when conditions.
;; To correctly resolve all the various :when conditions,
;; do not make any assumptions about which features are active.
;; Initially only consider non-:when implementations to be
;; active, then run through the list of unconfirmed :when
;; implementations and check their conditions against the list
;; of confirmed features. Continue doing this until no more
;; features are confirmed.
(let ((processing t)
(confirmed-features
(cl-remove-if ; Count unimplemented features as present.
(lambda (feat) (assq feat current-implementations))
explicit-features))
conditional-implementations when)
;; Sort all features by the presense of :when.
(dolist (impl current-implementations)
(if (plist-get (cdr impl) :when)
(push impl conditional-implementations)
(push (car impl) confirmed-features)))
(while processing
(setq processing nil)
;; Check for implementations which have satisfied :when
;; contions.
(dolist (impl conditional-implementations)
(setq when (plist-get (cdr impl) :when))
(when (cond
((symbolp when)
(memq when confirmed-features))
((consp when)
(not (cl-set-difference when confirmed-features))))
(push (car impl) confirmed-features)
(setq conditional-implementations
(delq impl conditional-implementations)
processing t))))
;; Now all that remains is implementations with unsatisfiable
;; :when conditions.
(dolist (impl conditional-implementations)
(setq current-implementations
(delq impl current-implementations))))
;; * Process ~:prevents~
;; Go through every implementation and for prevented features
;; 1. Remove them from current-implementations
;; 2. Go through require-records and remove them from the cdrs.
;; By modifying require-records in this way, features that are
;; only present due to a now-prevented feature will have a
;; nil cdr. We can then (recursively) check for these features
;; with `rassq' and remove them.
;; Since we used a queue rather than a stack when processing
;; :requires, we know that second order requires (i.e. :requires
;; of :requires) will come after after first order requires.
;; This means that should a n-th order require be prevented by
;; (n-1)-th order require, it will be removed before being
;; processed, and hence handled correctly.
(let (feats-to-remove removed null-require)
(dolist (impl current-implementations)
(setq feats-to-remove (org-ensure-list (plist-get (cdr impl) :prevents)))
(while feats-to-remove
;; Remove each of feats-to-remove.
(dolist (feat feats-to-remove)
(unless (memq feat removed)
(push feat removed)
(setq current-implementations
(delq (assq feat current-implementations)
current-implementations))
(when (assq feat require-records)
(setq require-records
(delq (assq feat require-records) require-records)))))
(dolist (rec require-records)
(setcdr rec (cl-set-difference (cdr rec) feats-to-remove)))
;; The features have now been removed.
(setq feats-to-remove nil)
;; Look for orphan requires.
(when (setq null-require (rassq nil require-records))
(push (car null-require) feats-to-remove)))))
;; Re-sort by ~:order~, to position reqirued features correctly.
(setq current-implementations
(sort current-implementations
(lambda (a b)
(< (or (plist-get (cdr a) :order) 0)
(or (plist-get (cdr b) :order) 0)))))
;; * Processing ~:before~ and ~:after~
;; To resolve dependency order, we will now perform a stable topological
;; sort on any DAGs that exist within current-implementations.
(org-export--feature-implementation-toposort
current-implementations)))
(defun org-export--feature-implementation-toposort (implementations)
"Perform a stable topological sort of IMPLEMENTATIONS.
The sort is performed based on the :before and :after properties.
See <https://en.wikipedia.org/wiki/Topological_sorting> for more information
on what this entails."
(let ((feature-indicies
(cl-loop
for elt in implementations
and index from 0
collect (cons (car elt) index)))
resolved-implementations
adj-list node-stack)
;; Build an adjacency list from :before and :after.
(dolist (impl implementations)
(push (list (car impl)) adj-list))
(dolist (impl implementations)
(let ((before (org-ensure-list (plist-get (cdr impl) :before)))
(after (org-ensure-list (plist-get (cdr impl) :after))))
(dolist (child before)
(push (car impl) (cdr (assq child adj-list))))
(when after
(setcdr (assq (car impl) adj-list)
(nconc (cdr (assq (car impl) adj-list))
after)))))
;; Initialise the node stack with the first implementation.
(setq node-stack (list (car implementations))
;; Make the order of adj-list match implementations.
adj-list
(mapcar
(lambda (entry)
(cons (car entry)
;; Sort edges according to feature order, to do
;; the DFS in order and make the result stable.
(sort (cdr entry)
(lambda (a b)
(< (or (alist-get a feature-indicies)
most-positive-fixnum)
(or (alist-get b feature-indicies)
most-positive-fixnum))))))
(nreverse adj-list)))
(while adj-list
(let ((deps (alist-get (caar node-stack) adj-list))
new-dep-found)
;; Look for any unresolved dependencies.
(while (and deps (not new-dep-found))
(if (not (assq (car deps) adj-list))
(setq deps (cdr deps))
;; Check the unresolved dependency is not part of a cycle.
(when (assq (car deps) node-stack)
(signal 'org-circular-feature-dependency
(format "Found a cycle in the feature dependency graph: %S"
(cons (car deps)
(nreverse (memq (car deps)
(nreverse
(mapcar #'car node-stack))))))))
;; Push the unresolved dependency to the top of the stack.
(push (assq (car deps) implementations)
node-stack)
(setq new-dep-found t)))
(unless new-dep-found
;; The top item of the stack has no unresolved dependencies.
;; Move it to the resolved list, and remove its entry from
;; adj-list to both mark it as such and ensure that
;; node-stack will not be incremented to it when/if the
;; stack is emptied.
(push (car node-stack) resolved-implementations)
(setq adj-list
(delq (assq (caar node-stack) adj-list) adj-list)
node-stack
(or (cdr node-stack)
(list (assq (caar adj-list) implementations)))))))
(nreverse resolved-implementations)))
(defun org-export-expand-feature-snippets (info &rest feature-implementations)
"Expand each of the feature :snippet keys in FEATURE-IMPLEMENTATIONS.
FEATURE-IMPLEMENTATIONS is expected to be a list of implementation
plists, if not provided explicitly it is extracted from the
:feature-implementations key of INFO. Note that an explicitly
provided nil FEATURE-IMPLEMENTATIONS is interpreted as no features.
Each implementation plist's :snippet value is expanded in order, in
the following manner:
- nil values are ignored
- functions are called with INFO, and must produce a string or nil
- variable symbols use the value, which must be a string or nil
- strings are included verbatim
- all other values throw an `error'.
\(fn INFO &optional FEATURE-IMPLEMENTATIONS)"
(let ((feat-impls
(cond
((not feature-implementations)
(plist-get info :feature-implementations))
((= (length feature-implementations) 1)
(car feature-implementations))
(t (signal 'wrong-number-of-arguments
`(org-export-expand-feature-snippets
,(1+ (length feature-implementations)))))))
expanded-snippets snippet value)
(dolist (impl feat-impls)
(setq snippet (plist-get (cdr impl) :snippet)
value (cond
((null snippet) nil)
((functionp snippet) (funcall snippet info))
((symbolp snippet) (symbol-value snippet))
((stringp snippet) snippet)
(t (error "org-export: The %s feature snippet %S is invalid (must be either nil, a function/variable symbol, or a string)"
(car impl) snippet))))
(cond
((stringp value)
(push value expanded-snippets))
(value ; Non-string value, could come from function or variable.
(error "org-export: The %s feature snippet %s must give nil or a string, but instead gave %S"
(car impl)
(cond
((and (functionp snippet) (symbolp snippet))
(format "function (`%s')" snippet))
((functionp snippet) "anonymous function")
(t (format "variable (`%s')" snippet)))
value))))
(nreverse expanded-snippets)))
(defun org-export-process-features (info)
"Install feature conditions/implementations in INFO, and resolve them.
See `org-export-detect-features' and `org-export-resolve-feature-implementations' for
more information on what this entails."
(org-export-install-features info)
(let* ((exp-features (org-export-detect-features info))
(resolved-implementations
(org-export-resolve-feature-implementations info exp-features)))
(plist-put info :feature-implementations resolved-implementations)
(plist-put info :features (mapcar #'car resolved-implementations))))
;;;###autoload
(defmacro org-export-update-features (backend &rest feature-property-value-lists)
"For BACKEND's export spec, set each FEATURE's :PROPERTY to VALUE.
The behaviour of this macro is best behaved with an example.
For instance, to add some preamble content from the variable
\"my-org-beamer-metropolis-tweaks\" when using the metropolis theme
with beamer export:
(org-export-update-features \\='beamer
(beamer-metropolis
:condition (string-match-p \"metropolis$\" (plist-get info :beamer-theme))
:snippet my-org-beamer-metropolis-tweaks
:order 3))
The modifies the beamer backend, either creating or updating the
\"beamer-metropolis\" feature. The :condition property adds a
condition which detects the feature, and all other properties are
applied to the feature's implementation plist. Setting
:condition to t means the feature will always be enabled, and
conversely setting :condition to nil means the feature will never
be enabled.
When setting the :condition and :snippet properties, any sexp is
is implicitly converted to,
(lambda (info) SEXPR)
Each (FEATURE . (:PROPERTY VALUE)) form that is processed is
taken from the single &rest argument
FEATURE-PROPERTY-VALUE-LISTS.
\(fn BACKEND &rest (FEATURE . (:PROPERTY VALUE)...)...)"
(declare (indent 1))
(org-with-gensyms (backend-struct the-entry the-condition the-feat-impl cond-feat)
(let ((backend-expr
(if (and (eq (car-safe backend) 'quote)
(symbolp (cadr backend))
(not (cddr backend)))
`(org-export-get-backend ',(cadr backend))
`(if (symbolp ,backend)
(org-export-get-backend ,backend)
backend)))
(backend-impls
(list 'aref backend-struct
(cl-struct-slot-offset 'org-export-backend 'feature-implementations)))
(backend-conds
(list 'aref backend-struct
(cl-struct-slot-offset 'org-export-backend 'feature-conditions)))
body condition-set-p implementation-set-p)
(dolist (feature-property-value-set feature-property-value-lists)
(when (eq (car feature-property-value-set) 'quote)
(pop feature-property-value-set))
(let ((features (car feature-property-value-set))
(property-value-pairs (cdr feature-property-value-set))
let-body property value)
(while property-value-pairs
(setq property (pop property-value-pairs)
value (pop property-value-pairs))
(cond
((consp value)
(unless (memq (car value) '(function quote))
(if (and (memq property '(:condition :snippet))
(not (functionp value)))
(setq value `(lambda (info) ,value))
(setq value (list 'quote value)))))
((memq value '(nil t))) ; Leave unmodified.
((symbolp value)
(setq value (list 'quote value))))
(if (eq property :condition)
(progn
(unless condition-set-p
(setq condition-set-p t))
(push
(if value
(let ((the-features (org-ensure-list features)))
`(let* ((,the-condition ,value)
(,the-entry (assoc ,the-condition ,backend-conds)))
(if ,the-entry
(setcdr ,the-entry
(append ',the-features (cdr ,the-entry)))
(push (cons ,the-condition ',the-features)
,backend-conds))))
(let ((single-feature
(if (consp features)
(intern (string-join (mapcar #'symbol-name features)
"-and-"))
features)))
`(dolist (,cond-feat ,backend-conds)
(cond
((equal (cdr ,cond-feat) (list ',single-feature))
(setf ,backend-conds (delq ,cond-feat ,backend-conds)))
((memq ',single-feature (cdr ,cond-feat))
(setcdr ,cond-feat
(delq ',single-feature (cdr ,cond-feat))))))))
body))
(unless implementation-set-p
(setq implementation-set-p t))
(push
(if let-body
`(plist-put (cdr ,the-feat-impl) ,property ,value)
`(setcdr ,the-feat-impl
(plist-put (cdr ,the-feat-impl) ,property ,value)))
let-body)))
(when let-body
(let ((the-feature
(if (consp features)
(intern (string-join (mapcar #'symbol-name features)
"-and-"))
features)))
(when (consp features)
(push
`(plist-put (cdr ,the-feat-impl) :when ',features)
let-body))
(push
`(let ((,the-feat-impl
(or (assoc ',the-feature ,backend-impls)
(car (push (list ',the-feature ,property nil)
,backend-impls)))))
,@(nreverse let-body))
body)))))
`(let ((,backend-struct ,backend-expr))
,@(and (not (org-export-backend-p backend-expr))
`((unless (org-export-backend-p ,backend-struct)
(error "`%s' is not a loaded export backend" ,backend))))
,@(nreverse body)
nil))))
;;; The Filter System
@ -3129,6 +3737,8 @@ still inferior to file-local settings."
(when (plist-get info :with-cite-processors)
(org-cite-process-citations info)
(org-cite-process-bibliography info))
;; Install all the feature conditions and implementations.
(org-export-process-features info)
info))
;;;###autoload
@ -5942,6 +6552,56 @@ INFO is the current export state, as a plist."
(when current-status
(push (cons text (nreverse current-status)) full-status))))
info nil org-element-recursive-objects)
;; When quotes are not balanced, treat them as apostrophes.
(setq full-status (nreverse full-status))
(let (primary-openings secondary-openings)
(dolist (substatus full-status)
(let ((status (cdr substatus)))
(while status
(pcase (car status)
(`apostrophe nil)
(`primary-opening
(push status primary-openings))
(`secondary-opening
(push status secondary-openings))
(`secondary-closing
(if secondary-openings
;; Remove matched opening.
(pop secondary-openings)
;; No matching openings for a given closing. Replace
;; it with apostrophe.
(setcar status 'apostrophe)))
(`primary-closing
(when secondary-openings
;; Some secondary opening quotes are not closed
;; within "...". Replace them all with apostrophes.
(dolist (opening secondary-openings)
(setcar opening 'apostrophe))
(setq secondary-openings nil))
(if primary-openings
;; Remove matched opening.
(pop primary-openings)
;; No matching openings for a given closing.
(error "This should no happen"))))
(setq status (cdr status)))))
(when primary-openings
;; Trailing unclosed "
(unless (= 1 (length primary-openings))
(error "This should not happen"))
;; Mark for not replacing.
(setcar (car primary-openings) nil)
;; Mark all the secondary openings and closings after
;; trailing unclosed " as apostrophes.
(let ((after-unbalanced-primary nil))
(dolist (substatus full-status)
(let ((status (cdr substatus)))
(while status
(when (eq status (car primary-openings))
(setq after-unbalanced-primary t))
(when after-unbalanced-primary
(when (memq (car status) '(secondary-opening secondary-closing))
(setcar status 'apostrophe)))
(setq status (cdr status))))))))
(puthash (cons parent (org-element-secondary-p s)) full-status cache)
(cdr (assq s full-status))))))
@ -6087,6 +6747,7 @@ them."
("cs" :default "Pokračování z předchozí strany")
("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")
("et" :default "Jätk eelmisele leheküljele" :html "J&#228;tk eelmisele lehek&#252;ljele" :utf-8 "Jätk eelmisele leheküljele")
("fa" :default "ادامه از صفحهٔ قبل")
("fr" :default "Suite de la page précédente")
("it" :default "Continua da pagina precedente")
@ -6107,6 +6768,7 @@ them."
("cs" :default "Pokračuje na další stránce")
("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")
("et" :default "Jätkub järgmisel leheküljel" :html "J&#228;tkub j&#228;rgmisel lehek&#252;ljel" :utf-8 "Jätkub järgmisel leheküljel")
("fa" :default "ادامه در صفحهٔ بعد")
("fr" :default "Suite page suivante")
("it" :default "Continua alla pagina successiva")
@ -6124,6 +6786,7 @@ them."
("tr" :default "Devamı sonraki sayfada"))
("Created"
("cs" :default "Vytvořeno")
("et" :default "Loodud")
("fa" :default "ساخته شده")
("nl" :default "Gemaakt op") ;; must be followed by a date or date+time
("nn" :default "Oppretta")
@ -6141,7 +6804,7 @@ them."
("de" :default "Datum")
("eo" :default "Dato")
("es" :default "Fecha")
("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
("et" :default "Kuupäev" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
("fa" :default "تاریخ")
("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
("hu" :html "D&aacute;tum")
@ -6168,7 +6831,7 @@ them."
("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")
("et" :default "Võrrand" :html "V&#245;rrand" :utf-8 "Võrrand")
("fa" :default "معادله")
("fr" :ascii "Equation" :default "Équation")
("is" :default "Jafna")
@ -6240,7 +6903,7 @@ them."
("de" :html "Fu&szlig;noten" :default "Fußnoten")
("eo" :default "Piednotoj")
("es" :ascii "Notas al pie de pagina" :html "Notas al pie de p&aacute;gina" :default "Notas al pie de página")
("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
("et" :default "Allmärkused" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
("fa" :default "پانوشت‌ها")
("fi" :default "Alaviitteet")
("fr" :default "Notes de bas de page")
@ -6363,6 +7026,7 @@ them."
("cs" :default "Reference")
("de" :default "Quellen")
("es" :default "Referencias")
("et" :default "Viited")
("fa" :default "منابع")
("fr" :ascii "References" :default "Références")
("it" :default "Riferimenti")
@ -6376,6 +7040,7 @@ them."
("tr" :default "Referanslar"))
("See figure %s"
("cs" :default "Viz obrázek %s")
("et" :default "Vaata joonist %s")
("fa" :default "نمایش شکل %s")
("fr" :default "cf. figure %s"
:html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s")
@ -6391,6 +7056,7 @@ them."
("tr" :default "bkz. şekil %s"))
("See listing %s"
("cs" :default "Viz program %s")
("et" :default "Vaata loendit %s")
("fa" :default "نمایش برنامه‌ریزی %s")
("fr" :default "cf. programme %s"
:html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s")
@ -6409,7 +7075,7 @@ them."
("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")
("et" :default "Vaata peatükki %s" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
("fa" :default "نمایش بخش %s")
("fr" :default "cf. section %s")
("it" :default "Vedi sezione %s")
@ -6429,6 +7095,7 @@ them."
("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
("See table %s"
("cs" :default "Viz tabulka %s")
("et" :default "Vaata tabelit %s")
("fa" :default "نمایش جدول %s")
("fr" :default "cf. tableau %s"
:html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s")

View File

@ -53,7 +53,7 @@ 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 java sqlite eshell
BTEST_OB_LANGUAGES = awk C fortran maxima lilypond octave perl python java sqlite eshell calc
# R # requires ESS to be installed and configured
# ruby # requires inf-ruby to be installed and configured
# extra packages to require for testing

View File

@ -0,0 +1,30 @@
#+latex_header: \usepackage{amsmath}
#+latex_header: \usepackage{amssymb}
* Inline fragments and LaTeX environments
:PROPERTIES:
:ID: 0b3807b3-69af-40cb-a27a-b380d54879cc
:END:
The LQR problem for a time-periodic system of the form
\begin{align}
\dot{x} = A(t) x + B(t) u, \quad t \in [0, \infty), \quad x(0) = x_i \label{eq:time-varying-system}\\
A(t+T) = A(t),\ B(t + T) = B(t) \nonumber
\end{align}
is as follows. With a quadratic form defined on \( (x,u) \) pairs
\begin{align}
\label{eq:quadratic-form}
\mathbf{q}(x, u) := \lim_{t_f \to \infty} \int_{0}^{t_f} \begin{bmatrix} x \\ u \end{bmatrix}^{\star} \begin{bmatrix}
Q & 0 \\
0 & r
\end{bmatrix} \begin{bmatrix} x \\ u \end{bmatrix} =: \lim_{t_f \to \infty} \int_{0}^{t_f} q(x,u) dt
\end{align}
with \( q \ge 0 \) and \( r \ge 0 \), find the infimum of the quadratic form \( \mathbf{q} \) subject to the dynamics:
\[
\inf_{x,u} \mathbf{q}(x,u).
\]
\begin{align}
\label{eq:lqr-inf-via-duality}
\inf_{x, u} \mathbf{q}(x, u) = x_i^{\star} \bar{\lambda}(0) x_i,
\end{align}
where \( \bar{\lambda} \) is the maximal solution of the differential linear matrix inequality over \( [0, t] \).

View File

@ -0,0 +1,115 @@
;;; test-ob-calc.el --- tests for ob-calc.el -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Visuwesh
;; Author: Visuwesh <visuweshm@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 <https://www.gnu.org/licenses/>.
;;; Code:
(require 'ob-calc)
(unless (featurep 'ob-calc)
(signal 'missing-test-dependency "Support for Calc code blocks"))
(ert-deftest ob-calc/simple-program-mult ()
"Test of simple multiplication."
(org-test-with-temp-text "\
#+BEGIN_SRC calc :results silent
1 * 2
#+END_SRC"
(should (equal "2" (org-babel-execute-src-block)))))
(ert-deftest ob-calc/simple-program-arith ()
"Test of simple arithmetic."
(org-test-with-temp-text "\
#+BEGIN_SRC calc :results silent
12 + 16 - 1
#+END_SRC"
(should (equal "27" (org-babel-execute-src-block)))))
(ert-deftest ob-calc/simple-program-symbolic ()
"Test of simple symbolic algebra."
(org-test-with-temp-text "\
#+BEGIN_SRC calc :results silent
inv(a)
#+END_SRC"
(should (equal "1 / a" (org-babel-execute-src-block)))))
(ert-deftest ob-calc/matrix-inversion ()
"Test of a matrix inversion."
(org-test-with-temp-text "\
#+NAME: ob-calc-table-1
| 1 | 2 | 3 |
| 5 | 6 | 7 |
| 9 | 14 | 11 |
<point>#+BEGIN_SRC calc :results silent :var a=ob-calc-table-1
inv(a)
#+END_SRC "
(should (equal "[[-1, 0.625, -0.125], [0.25, -0.5, 0.25], [0.5, 0.125, -0.125]]"
(org-babel-execute-src-block)))))
(ert-deftest ob-calc/matrix-algebra ()
"Test of simple matrix algebra."
(org-test-with-temp-text "\
#+NAME: ob-calc-table-2
| 1 | 2 | 3 | 4 | 5 |
<point>#+BEGIN_SRC calc :results silent :var a=ob-calc-table-2
a*2 - 2
#+END_SRC"
(should (equal "[0, 2, 4, 6, 8]"
(org-babel-execute-src-block)))))
(ert-deftest ob-calc/matrix-mean ()
"Test of simple mean of a vector."
(org-test-with-temp-text "\
#+NAME: ob-calc-table-2
| 1 | 2 | 3 | 4 | 5 |
<point>#+BEGIN_SRC calc :results silent :var a=ob-calc-table-2
vmean(a)
#+END_SRC"
(should (equal "3"
(org-babel-execute-src-block)))))
(ert-deftest ob-calc/matrix-correct-conv-column ()
"Test of conversion of column table to Calc format."
(org-test-with-temp-text "\
#+NAME: ob-calc-table-3
| 1 |
| 2 |
| 3 |
<point>#+BEGIN_SRC calc :results silent :var a=ob-calc-table-3
a
#+END_SRC"
(should (equal "[[1], [2], [3]]"
(org-babel-execute-src-block)))))
(ert-deftest ob-calc/matrix-correct-conv-row ()
"Test of conversion of row table to Calc format."
(org-test-with-temp-text "\
#+NAME: ob-calc-table-2
| 1 | 2 | 3 | 4 | 5 |
<point>#+BEGIN_SRC calc :results silent :var a=ob-calc-table-2
a
#+END_SRC"
(should (equal "[1, 2, 3, 4, 5]"
(org-babel-execute-src-block)))))
(provide 'test-ob-calc)
;;; test-ob-calc.el ends here

View File

@ -0,0 +1,75 @@
;;; test-ob-comint.el -*- lexical-binding: t; -*-
;; Copyright (c) 2024 Matthew Trzcinski
;; Authors: Matthew Trzcinski
;; 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 <https://www.gnu.org/licenses/>.
;;; Comment:
;; See testing/README for how to run tests.
;;; Requirements:
;;; Code:
(ert-deftest test-org-babel-comint/prompt-filter-removes-prompt ()
"Test that prompt is actually removed."
(let* ((prompt "org_babel_sh_prompt> ")
(results "org_babel_sh_prompt> echo 'ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59'
# print message
echo \"hello world\"
echo 'ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59'
ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> org_babel_sh_prompt> \"hello world\"
org_babel_sh_prompt> ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> "))
(should (string=
(org-trim (string-join (mapcar #'org-trim (org-babel-comint--prompt-filter results prompt)) "\n") "\n")
"echo 'ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59'
# print message
echo \"hello world\"
echo 'ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59'
ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59
\"hello world\"
ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59"))))
(ert-deftest test-org-babel-comint/echo-filter-removes-echo ()
"Test that echo is actually removed."
(let* ((echo "echo 'ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59'
# print message
echo \"hello world\"
echo 'ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59'")
(result "org_babel_sh_prompt> echo 'ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59'
# print message
echo \"hello world\"
echo 'ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59'
ob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> org_babel_sh_prompt> \"hello world\"
org_babel_sh_prompt> ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> "))
(should (string=
(org-babel-comint--echo-filter result echo)
"\nob_comint_async_shell_start_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> org_babel_sh_prompt> \"hello world\"
org_babel_sh_prompt> ob_comint_async_shell_end_d78ac49f-dc8a-4c39-827c-c93225484d59
org_babel_sh_prompt> "))))
(provide 'test-ob-comint)
;;; test-ob-comint.el ends here

View File

@ -1,4 +1,4 @@
;;; test-ob-python.el --- tests for ob-python.el -*- lexical-binding: t; -*-
;;; test-ob-julia.el --- tests for ob-julia.el -*- lexical-binding: t; -*-
;; Copyright (c) 2011-2014, 2019, 2021 Eric Schulte
;; Authors: Pedro Bruel, based on test-ob-python.el by Eric Schulte

View File

@ -129,6 +129,30 @@ echo 2<point>
(if (should (string= ": 1\n: 2\n" (buffer-substring-no-properties (point) (point-max))))
(kill-buffer session-name)))))
(ert-deftest test-ob-shell/session-async-results ()
"Test that async evaluation removes prompt from results."
(let* ((session-name "test-ob-shell/session-async-results")
(kill-buffer-query-functions nil)
(start-time (current-time))
(wait-time (time-add start-time 3))
uuid-placeholder)
(org-test-with-temp-text
(concat "#+begin_src sh :session " session-name " :async t
# print message
echo \"hello world\"<point>
#+end_src")
(setq uuid-placeholder (org-trim (org-babel-execute-src-block)))
(catch 'too-long
(while (string-match uuid-placeholder (buffer-string))
(progn
(sleep-for 0.01)
(when (time-less-p wait-time (current-time))
(throw 'too-long (ert-fail "Took too long to get result from callback"))))))
(search-forward "#+results")
(beginning-of-line 2)
(if (should (string= ": hello world\n" (buffer-substring-no-properties (point) (point-max))))
(kill-buffer session-name)))))
(ert-deftest test-ob-shell/generic-uses-no-arrays ()
"Test generic serialization of array into a single string."
(org-test-with-temp-text

View File

@ -1,4 +1,4 @@
;;; test-org-bbdb.el --- tests for org-bbdb.el -*- lexical-binding: t; -*-
;;; test-ol-bbdb.el --- tests for ol-bbdb.el -*- lexical-binding: t; -*-
;; Copyright (C) 2018, 2019 Marco Wahl
@ -20,7 +20,7 @@
;;; Commentary:
;; Test some of org-bbdb.el.
;; Test some of ol-bbdb.el.
;;; Code:

View File

@ -1157,6 +1157,15 @@ CLOCK: [2023-10-13 Fri 14:40]--[2023-10-13 Fri 14:51] => 0:11"
(org-element-property :value clock))
"[2012-01-01 sun. 00:01]"))
(should-not (org-element-property :duration clock)))
;; clock string should not be case-sensitive.
(let ((clock (org-test-with-temp-text "Clock: [2012-01-01 sun. 00:01]"
(org-element-at-point))))
(should (eq (org-element-property :status clock) 'running))
(should
(equal (org-element-property :raw-value
(org-element-property :value clock))
"[2012-01-01 sun. 00:01]"))
(should-not (org-element-property :duration clock)))
;; Closed clock.
(let ((clock
(org-test-with-temp-text

View File

@ -1,4 +1,4 @@
;;; test-org.el --- tests for org.el -*- lexical-binding: t; -*-
;;; test-org-fold.el --- tests for org-fold.el -*- lexical-binding: t; -*-
;; Authors: Ihor Radchenko

View File

@ -0,0 +1,344 @@
;;; test-org-latex-preview.el --- tests for org-latex-preview.el -*- lexical-binding: t; -*-
;; Copyright (c) 2023 Karthik Chikmagalur
;; Authors: Karthik Chikmagalur
;; 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 <https://www.gnu.org/licenses/>.
;;; Code:
(unless (featurep 'org-latex-preview)
(signal 'missing-test-dependency "Support for LaTeX previews"))
(require 'org-latex-preview)
(require 'cl-lib)
(ert-deftest test-org-latex-preview/assert ()
(should t))
;; Test for executables required for preview generation
(org-test-for-executable "latex")
(org-test-for-executable "dvisvgm")
(org-test-for-executable "dvipng")
;; Should we test imagemagick?
;; (org-test-for-executable "convert")
;; fragment pre-processing tests
;;; Collect fragments
(ert-deftest test-org-latex-preview/collect-fragments-inline ()
"Test LaTeX fragment collection"
(let ((elements
'((latex-fragment
(:value "\\( q \\ge 0 \\)" :begin 770 :end 784 :post-blank 1 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-fragment
(:value "\\( r \\ge 0 \\)" :begin 788 :end 801 :post-blank 0 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments")))))))))))
(org-test-at-id
"0b3807b3-69af-40cb-a27a-b380d54879cc"
(should
(equal (org-latex-preview-collect-fragments 765 807) elements))
(should
(equal (org-latex-preview--construct-entries elements)
'(((770 783 "\\( q \\ge 0 \\)")
(788 801 "\\( r \\ge 0 \\)"))
nil)))
(should
(equal (org-latex-preview--construct-entries elements)
(org-latex-preview--construct-entries elements 'with-numbering))))))
(ert-deftest test-org-latex-preview/collect-fragments-environment ()
"Test LaTeX fragment collection"
(let ((elements
'((latex-environment
(:begin 241 :end 412 :value "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n" :post-blank 0 :post-affiliated 241 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments")))))))))
(org-test-at-id
"0b3807b3-69af-40cb-a27a-b380d54879cc"
(should
(equal (org-latex-preview-collect-fragments 186 426) elements))
(should
(equal (org-latex-preview--construct-entries elements)
'(((241 411 "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n"))
nil)))
(should
(equal (org-latex-preview--construct-entries elements 'with-numbering)
'(((241 411 "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n"))
(1)))))))
(ert-deftest test-org-latex-preview/collect-fragments-all ()
"Test LaTeX fragment collection"
(let ((elements
'((latex-environment
(:begin 241 :end 412 :value "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n" :post-blank 0 :post-affiliated 241 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))
(latex-fragment
(:value "\\( (x,u) \\)" :begin 460 :end 472 :post-blank 1 :parent
(paragraph
(:begin 412 :end 478 :contents-begin 412 :contents-end 478 :post-blank 0 :post-affiliated 412 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-environment
(:begin 478 :end 765 :value "\\begin{align}\n\\label{eq:quadratic-form}\n\\mathbf{q}(x, u) := \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} \\begin{bmatrix} x \\\\ u \\end{bmatrix}^{\\star} \\begin{bmatrix}\nQ & 0 \\\\\n0 & r\n \\end{bmatrix} \\begin{bmatrix} x \\\\ u \\end{bmatrix} =: \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} q(x,u) dt\n\\end{align}\n" :post-blank 0 :post-affiliated 478 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))
(latex-fragment
(:value "\\( q \\ge 0 \\)" :begin 770 :end 784 :post-blank 1 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-fragment
(:value "\\( r \\ge 0 \\)" :begin 788 :end 801 :post-blank 0 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-fragment
(:value "\\( \\mathbf{q} \\)" :begin 842 :end 859 :post-blank 1 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-fragment
(:value "\\[\n\\inf_{x,u} \\mathbf{q}(x,u).\n\\]" :begin 884 :end 917 :post-blank 0 :parent
(paragraph
(:begin 765 :end 918 :contents-begin 765 :contents-end 918 :post-blank 0 :post-affiliated 765 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-environment
(:begin 918 :end 1040 :value "\\begin{align}\n\\label{eq:lqr-inf-via-duality}\n\\inf_{x, u} \\mathbf{q}(x, u) = x_i^{\\star} \\bar{\\lambda}(0) x_i,\n\\end{align}\n" :post-blank 0 :post-affiliated 918 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))
(latex-fragment
(:value "\\( \\bar{\\lambda} \\)" :begin 1046 :end 1066 :post-blank 1 :parent
(paragraph
(:begin 1040 :end 1154 :contents-begin 1040 :contents-end 1154 :post-blank 0 :post-affiliated 1040 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments"))))))))
(latex-fragment
(:value "\\( [0, t] \\)" :begin 1140 :end 1152 :post-blank 0 :parent
(paragraph
(:begin 1040 :end 1154 :contents-begin 1040 :contents-end 1154 :post-blank 0 :post-affiliated 1040 :mode nil :granularity element :parent
(section
(:begin 118 :end 1154 :contents-begin 118 :contents-end 1154 :robust-begin 118 :robust-end 1152 :post-blank 0 :post-affiliated 118 :mode section :granularity element :parent
(headline
(:raw-value "Inline fragments and LaTeX environments" :begin 76 :end 1154 :pre-blank 0 :contents-begin 118 :contents-end 1154 :robust-begin 184 :robust-end 1152 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 76 :ID "0b3807b3-69af-40cb-a27a-b380d54879cc" :title "Inline fragments and LaTeX environments")))))))))))
(org-test-at-id
"0b3807b3-69af-40cb-a27a-b380d54879cc"
(should
(equal (org-latex-preview-collect-fragments) elements))
(should (equal (org-latex-preview--construct-entries elements)
'(((241 411 "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n")
(460 471 "\\( (x,u) \\)")
(478 764 "\\begin{align}\n\\label{eq:quadratic-form}\n\\mathbf{q}(x, u) := \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} \\begin{bmatrix} x \\\\ u \\end{bmatrix}^{\\star} \\begin{bmatrix}\nQ & 0 \\\\\n0 & r\n \\end{bmatrix} \\begin{bmatrix} x \\\\ u \\end{bmatrix} =: \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} q(x,u) dt\n\\end{align}\n")
(770 783 "\\( q \\ge 0 \\)")
(788 801 "\\( r \\ge 0 \\)")
(842 858 "\\( \\mathbf{q} \\)")
(884 917 "\\[\n\\inf_{x,u} \\mathbf{q}(x,u).\n\\]")
(918 1039 "\\begin{align}\n\\label{eq:lqr-inf-via-duality}\n\\inf_{x, u} \\mathbf{q}(x, u) = x_i^{\\star} \\bar{\\lambda}(0) x_i,\n\\end{align}\n")
(1046 1065 "\\( \\bar{\\lambda} \\)")
(1140 1152 "\\( [0, t] \\)"))
nil)))
(should (equal (org-latex-preview--construct-entries elements 'with-numbering)
'(((241 411 "\\begin{align}\n\\dot{x} = A(t) x + B(t) u, \\quad t \\in [0, \\infty), \\quad x(0) = x_i \\label{eq:time-varying-system}\\\\\nA(t+T) = A(t),\\ B(t + T) = B(t) \\nonumber\n\\end{align}\n")
(460 471 "\\( (x,u) \\)")
(478 764 "\\begin{align}\n\\label{eq:quadratic-form}\n\\mathbf{q}(x, u) := \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} \\begin{bmatrix} x \\\\ u \\end{bmatrix}^{\\star} \\begin{bmatrix}\nQ & 0 \\\\\n0 & r\n \\end{bmatrix} \\begin{bmatrix} x \\\\ u \\end{bmatrix} =: \\lim_{t_f \\to \\infty} \\int_{0}^{t_f} q(x,u) dt\n\\end{align}\n")
(770 783 "\\( q \\ge 0 \\)")
(788 801 "\\( r \\ge 0 \\)")
(842 858 "\\( \\mathbf{q} \\)")
(884 917 "\\[\n\\inf_{x,u} \\mathbf{q}(x,u).\n\\]")
(918 1039 "\\begin{align}\n\\label{eq:lqr-inf-via-duality}\n\\inf_{x, u} \\mathbf{q}(x, u) = x_i^{\\star} \\bar{\\lambda}(0) x_i,\n\\end{align}\n")
(1046 1065 "\\( \\bar{\\lambda} \\)")
(1140 1152 "\\( [0, t] \\)"))
(1 nil 2 nil nil nil nil 4 nil nil)))))))
;;; Set up overlays
(ert-deftest test-org-latex-preview/ensure-overlay ()
(org-test-at-id "0b3807b3-69af-40cb-a27a-b380d54879cc"
(org-latex-preview-clear-overlays (point-min) (point-max))
(let* ((elements (org-latex-preview-collect-fragments))
(entries (car (org-latex-preview--construct-entries elements)))
(ov) (all-ovs))
(pcase-dolist(`(,beg ,end ,value) entries)
(setq ov (org-latex-preview--ensure-overlay beg end))
(push ov all-ovs)
(should (eq (get-char-property beg 'org-overlay-type) 'org-latex-overlay))
(should (eq (overlay-get ov 'org-overlay-type) 'org-latex-overlay))
(should (eq (overlay-get ov 'evaporate) t))
(should (eq (overlay-get ov 'priority) org-latex-preview--overlay-priority))
(should (equal (overlay-get ov 'modification-hooks)
(list #'org-latex-preview-auto--mark-overlay-modified)))
(should (equal (overlay-get ov 'insert-in-front-hooks)
(list #'org-latex-preview-auto--insert-front-handler)))
(should (equal (overlay-get ov 'insert-behind-hooks)
(list #'org-latex-preview-auto--insert-behind-handler))))
(should (eq (length all-ovs) (length elements))))
(org-latex-preview-clear-overlays (point-min) (point-max))))
;; Precompilation test
;; TODO
;; Process fragments
;;; No precompilation, no caching
(ert-deftest test-org-latex-preview/place-previews-1 ()
(org-test-at-id "0b3807b3-69af-40cb-a27a-b380d54879cc"
(let ((org-latex-preview-process-precompiled nil)
(org-latex-preview-cache 'temp)
(org-latex-preview-process-default 'dvisvgm))
(org-latex-preview-auto-mode -1)
(goto-char 255)
(let ((element (org-element-context)))
(should (eq (org-element-type element) 'latex-environment))
(org-latex-preview-clear-cache (org-element-property :begin element)
(org-element-property :end element))
(apply #'org-async-wait-for
(org-latex-preview--place-from-elements
org-latex-preview-process-default
(list element)))
(let ((ov (cl-some (lambda (o) (and (eq (overlay-get o 'org-overlay-type)
'org-latex-overlay)
o))
(overlays-at (point)))))
(should (overlayp ov))
(let ((display (overlay-get ov 'display))
(face (overlay-get ov 'face))
(hidden-face (overlay-get ov 'hidden-face))
(preview-image (overlay-get ov 'preview-image)))
;; Image properties
(should (consp display))
(should (eq (car display) 'image))
(should (eq (plist-get (cdr display) :type) 'svg))
(should (stringp (plist-get (cdr display) :file)))
(should (string-suffix-p ".svg" (plist-get (cdr display) :file)))
(should (eq preview-image display))
;; Face properties
(should (eq face 'default))
(should (eq hidden-face face))))))))
(ert-deftest test-org-latex-preview/place-previews-all ()
(org-test-at-id "0b3807b3-69af-40cb-a27a-b380d54879cc"
(let ((org-latex-preview-process-precompiled nil)
(org-latex-preview-cache 'temp)
(org-latex-preview-process-default 'dvisvgm))
(org-latex-preview-auto-mode -1)
(org-latex-preview-clear-cache (point-min) (point-max))
(let ((elements (org-latex-preview-collect-fragments)))
(apply #'org-async-wait-for
(org-latex-preview--place-from-elements
org-latex-preview-process-default
elements))
(dolist (element elements)
(let ((ov (cl-some (lambda (o) (and (eq (overlay-get o 'org-overlay-type)
'org-latex-overlay)
o))
(overlays-at (org-element-property :begin element)))))
(should (overlayp ov))
(let ((display (overlay-get ov 'display))
(face (overlay-get ov 'face))
(hidden-face (overlay-get ov 'hidden-face))
(preview-image (overlay-get ov 'preview-image)))
;; Image properties
(should (consp display))
(should (eq (car display) 'image))
(should (eq (plist-get (cdr display) :type) 'svg))
(should (stringp (plist-get (cdr display) :file)))
(should (string-suffix-p ".svg" (plist-get (cdr display) :file)))
(should (eq preview-image display))
;; Face properties
(should (eq face 'default))
(should (eq hidden-face face)))))
(org-latex-preview-clear-cache (point-min) (point-max))))))
;; TODO: Test with precompilation
;; TODO: Test with caching
;; dvisvgm filter+callback test
;; dvipng filter+callback test
;; imagemagick filter+callback test
;; TODO
;; Color extraction
;; TODO
;; Scaling
;; TODO
;; Caching
;; TODO
;;; clear-cache test
;; Numbering
;; TODO
;; org-latex-preview-auto-mode
;; TODO
;; live previews
;; TODO
;; lualatex-specific tests
;; xelatex-specific tests
(provide 'test-org-latex-preview)
;;; test-org-latex-preview.el ends here

View File

@ -1,4 +1,4 @@
;;; test-org-tempo.el --- Tests for test-org-tempo.el -*- lexical-binding: t; -*-
;;; test-org-tempo.el --- Tests for org-tempo.el -*- lexical-binding: t; -*-
;; Copyright (C) 2017, 2019 Rasmus Pank Roulund

View File

@ -9590,6 +9590,85 @@ two
(string-match-p "\\`Invalid format.*%2" err-text))
err)))))
;;; LaTeX-related functions.
(ert-deftest test-org/format-latex-as-html ()
"Test shell special characters escaping in `org-format-latex-as-html'."
;; printf is only available in POSIX-compatible shells.
(skip-unless (not (memq system-type '(ms-dos windows-nt))))
(let ((org-latex-to-html-convert-command
"printf \"<I%%sI>\" %i"))
;; No backslashes added by `shell-quote-argumet'
;; are leaked to command arguments. See e.g. dash(1) "Double Quotes":
;;
;; The backslash inside double quotes is historically weird,
;; and serves to quote only the following characters:
;; $ ` " \ <newline>.
;; Otherwise it remains literal.
;;
;; Actually extra backslashes may appear if a user adds
;; double quotes around "%i", however it is not subject
;; of this test.
(should
(equal "<I(|)`[[\\]]{}#$'!I>"
(org-format-latex-as-html "(|)`[[\\]]{}#$'!")))
;; The following tests generate shell errors if %i
;; substitution is not passed throuhg `shell-quote-argument'.
;; Multiple words.
(should
(equal "<Iwords ; |I>"
(org-format-latex-as-html "words ; |")))
;; Bypass single quote.
;; The same snippet causes shell error if '%i' is wrapped
;; in single quotes in user configuration.
(should
(equal "<Iapostrophe' ; |I>"
(org-format-latex-as-html "apostrophe' ; |")))
;; Bypass double quote.
;; Double quotes around "%i" in user configuration leads
;; to extra backslashes (see above), however likely
;; such user error can not cause execution of the argument
;; as raw shell commands.
(should
(equal "<Iquote\" ; |I>"
(org-format-latex-as-html "quote\" ; |")))))
(defun test-org/extract-mathml-math (xml)
"Extract body from result of `org-create-math-formula'."
(and (string-match "<math[^>]*>\\(\\(?:.\\|\n\\)*\\)</math>" xml)
(match-string 1 xml)))
(ert-deftest test-org/create-math-formula ()
"Test shell special characters escaping in `org-create-math-formula'."
;; printf is only available in POSIX-compatible shells.
(skip-unless (not (memq system-type '(ms-dos windows-nt))))
;; The function requires <math>...</math> elements.
(let ((org-latex-to-mathml-convert-command
"printf \"<math xmlns=\\\"http://www.w3.org/1998/Math/MathML\\\"><I%%sI></math>\" %i >%o"))
;; See comments in `test-org/format-latex-as-html'.
;;
;; No backslashes added by `shell-quote-argumet'
;; are leaked to command arguments.
(should (equal "<I(|)`[[\\]]{}#$'!I>"
(test-org/extract-mathml-math
(org-create-math-formula "(|)`[[\\]]{}#$'!"))))
;; Multiple words.
(should
(equal "<Iwords ; |I>"
(test-org/extract-mathml-math
(org-create-math-formula "words ; |"))))
;; Bypass single quote.
(should
(equal "<Iapostrophe' ; |I>"
(test-org/extract-mathml-math
(org-create-math-formula "apostrophe' ; |"))))
;; Bypass double quote.
(should
(equal "<Iquote\" ; |I>"
(test-org/extract-mathml-math
(org-create-math-formula "quote\" ; |"))))))
(provide 'test-org)
;;; test-org.el ends here

View File

@ -1,4 +1,4 @@
;;; test-ox-latex.el --- tests for ox-latex.el -*- lexical-binding: t; -*-
;;; test-ox-ascii.el --- tests for ox-ascii.el -*- lexical-binding: t; -*-
;; Copyright (C) 2023 Ihor Radchenko

View File

@ -0,0 +1,110 @@
;;; test-ox-beamer.el --- tests for ox-beamer.el -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Leo Butler
;; Author: Leo Butler <leo.butler@umanitoba.ca>
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Tests checking validity of Org Beamer export output.
;;; Code:
(require 'ox-beamer nil t)
(unless (featurep 'ox-beamer)
(signal 'missing-test-dependency "org-export-beamer"))
(ert-deftest ox-beamer/orgframe ()
"Test that `org-beamer-frame-environment' is defined and used."
(org-test-with-exported-text
'beamer
"#+OPTIONS: toc:nil
* A frame
Here is an example:
#+begin_example
\\begin{frame}
...
\\end{frame}
#+end_example
"
(goto-char (point-min))
(should (search-forward (concat "\\newenvironment<>{" org-beamer-frame-environment "}") nil t))
(should (search-forward (concat "\\begin{" org-beamer-frame-environment "}") nil t))
(should (search-forward (concat "\\end{" org-beamer-frame-environment "}") nil t))))
(ert-deftest ox-beamer/orgframe-in-example ()
"Test that `org-beamer-frame-environment' is not defined."
(org-test-with-exported-text
'beamer
(concat "#+OPTIONS: toc:nil
* A frame
Here is an example:
#+begin_example
\\begin{" org-beamer-frame-environment "}
...
\\end{" org-beamer-frame-environment "}
#+end_example
")
(goto-char (point-min))
(should-not (search-forward
(concat "\\newenvironment<>{" org-beamer-frame-environment "}") nil t))
(forward-line)
(should (search-forward (concat "\\begin{frame}") nil t))
(should (search-forward (concat "\\begin{" org-beamer-frame-environment "}")))
(should (search-forward (concat "\\end{" org-beamer-frame-environment "}")))
(should (search-forward (concat "\\end{frame}") nil t))))
(ert-deftest ox-beamer/orgframe-in-one-example ()
"Test that `org-beamer-frame-environment' is defined.
First frame should use \"frame\" environment, the second uses
`org-beamer-frame-environment'."
(org-test-with-exported-text
'beamer
(concat "#+OPTIONS: toc:nil
* A frame
Here is an example:
#+begin_example
\\begin{" org-beamer-frame-environment "}
...
\\end{" org-beamer-frame-environment "}
#+end_example
* A second frame
Here is a second example:
#+begin_example
\\begin{frame}
...
\\end{frame}
#+end_example
")
(goto-char (point-min))
(should (search-forward
(concat "\\newenvironment<>{" org-beamer-frame-environment "}") nil t))
(forward-line)
(org-test-ignore-duplicate
(should (search-forward (concat "\\begin{frame}") nil t))
(should (search-forward (concat "\\begin{" org-beamer-frame-environment "}")))
(should (search-forward (concat "\\end{" org-beamer-frame-environment "}")))
(should (search-forward (concat "\\end{frame}") nil t))
(should (search-forward (concat "\\begin{" org-beamer-frame-environment "}")))
(should (search-forward (concat "\\begin{frame}") nil t))
(should (search-forward (concat "\\end{frame}") nil t))
(should (search-forward (concat "\\end{" org-beamer-frame-environment "}"))))))
(provide 'test-ox-beamer)
;;; test-ox-beamer.el ends here

View File

@ -1,4 +1,4 @@
;;; test-ox-html.el --- Tests for ox-html.el
;;; test-ox-html.el --- Tests for ox-html.el -*- lexical-binding: t; -*-
;; Copyright (C) 2022 Rudolf Adamkovič

View File

@ -1,4 +1,4 @@
;;; test-ox-texinfo.el --- Tests for ox-texinfo.el
;;; test-ox-texinfo.el --- Tests for ox-texinfo.el -*- lexical-binding: t; -*-
;; Copyright (C) 2022 Rudolf Adamkovič

View File

@ -2140,6 +2140,120 @@ Footnotes[fn:2], foot[fn:test] and [fn:inline:inline footnote]
(bold . (lambda (bold contents info) (concat contents "!")))))
'(:with-emphasize t)))))
;;; Export features
(ert-deftest test-org-export/feature-resolution ()
"Test the behaviour of `org-export-resolve-feature-implementations'"
;; Check implementations for listed features are given.
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a) (b) (c)))
'((a) (b) (c))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a)))
'((a))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a) '((a) (b) (c)))
'((a))))
;; Check depencency resolution.
(should
(equal (org-export-resolve-feature-implementations
nil '(a) '((a :requires b) (b) (c)))
'((a :requires b) (b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a) '((a :requires (b c)) (b) (c)))
'((a :requires (b c)) (b) (c))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a) '((a :requires b) (b :requires c) (c)))
'((a :requires b) (b :requires c) (c))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :prevents b) (b) (c)))
'((a :prevents b) (c))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :prevents (b c)) (b) (c)))
'((a :prevents (b c)))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c d) '((a :requires (b c)) (b) (c) (d :prevents b)))
'((a :requires (b c)) (c) (d :prevents b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c d) '((a :requires (b c)) (b) (c :prevents b)))
'((a :requires (b c)) (c :prevents b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a d) '((a :requires b) (b :requires c) (c) (d :prevents a)))
'((d :prevents a))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c d) '((a :requires b) (b :requires c) (c) (d :prevents a)))
'((b :requires c) (c) (d :prevents a))))
(should-error
(org-export-resolve-feature-implementations
nil '(a) '((a :requires b)))
:type 'org-missing-feature-dependency)
;; Check application of the :when condition.
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :when b) (b)))
'((a :when b) (b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :when (b c)) (b) (c)))
'((a :when (b c)) (b) (c))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a) (b) (c :when (a b))))
'((a) (b) (c :when (a b)))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :when b) (b :when c) (c)))
'((a :when b) (b :when c) (c))))
;; Check simple ordering.
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :order 3) (b :order 1) (c :order 2)))
'((b :order 1) (c :order 2) (a :order 3))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :order 1) (b) (c :order -1)))
'((c :order -1) (b) (a :order 1))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a) '((a :order 1 :requires b) (b :requires c) (c :order -1)))
'((c :order -1) (b :requires c) (a :order 1 :requires b))))
;; Check before/after ordering.
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :after (b c)) (b) (c)))
'((b) (c) (a :after (b c)))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a :after b) (b :after c) (c)))
'((c) (b :after c) (a :after b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a) (b) (c :before (a b))))
'((c :before (a b)) (a) (b))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a) (b :before a) (c :before b)))
'((c :before b) (b :before a) (a))))
(should
(equal (org-export-resolve-feature-implementations
nil '(a b c) '((a) (b :after c :before a) (c)))
'((c) (b :after c :before a) (a))))
(should-error ; Circular dependency
(org-export-resolve-feature-implementations
nil '(a b) '((a :after b) (b :after a)))
:type 'org-circular-feature-dependency))
;;; Comments
@ -4134,9 +4248,9 @@ This test does not cover listings and custom environments."
;; Opening quotes: at the beginning of a paragraph.
(should
(equal
'("&ldquo;begin")
'("&ldquo;begin&rdquo;")
(let ((org-export-default-language "en"))
(org-test-with-parsed-data "\"begin"
(org-test-with-parsed-data "\"begin\""
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :html info))
info)))))
@ -4267,6 +4381,39 @@ This test does not cover listings and custom environments."
(org-test-with-parsed-data "*\"foo\"*"
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :html info))
info nil nil t)))))
;; Unmatched quotes.
(should
(equal '("\\guillemotleft{}my friends' party and the students' papers\\guillemotright{} \\guillemotleft{}``mothers''\\guillemotright{}")
(let ((org-export-default-language "es"))
(org-test-with-parsed-data
"\"my friends' party and the students' papers\" \"'mothers'\""
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :latex info))
info nil nil t)))))
(should
(equal '("\"'mothers'")
(let ((org-export-default-language "es"))
(org-test-with-parsed-data
"\"'mothers'"
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :latex info))
info nil nil t)))))
(should
(equal '("\"'mothers " "end'")
(let ((org-export-default-language "es"))
(org-test-with-parsed-data
"\"'mothers =verbatim= end'"
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :latex info))
info nil nil t)))))
(should
(equal '("\\guillemotleft{}να 'ρθώ το βράδυ\\guillemotright{}")
(let ((org-export-default-language "el"))
(org-test-with-parsed-data
"\"να 'ρθώ το βράδυ\""
(org-element-map tree 'plain-text
(lambda (s) (org-export-activate-smart-quotes s :latex info))
info nil nil t))))))

View File

@ -1,4 +1,4 @@
;;; test-property-inheritance.el --- tests for property-inheritance.el -*- lexical-binding: t; -*-
;;; test-property-inheritance.el --- tests of property inheritance -*- lexical-binding: t; -*-
;; Copyright (c) 2011-2014, 2019 Eric Schulte
;; Authors: Eric Schulte