org export filter

I am writing an org-export-filter to be able to use the \legend command from ccaption package in a line starting with #+caption.

This way, the following code:

#+attr_latex: :options angle=45
#+caption[my short caption]: Long caption \legend{some text}
[[file:fig1.png]]


will be exported into:

\begin{figure}[htbp]
\centering
\includegraphics[angle=45,width=.9\linewidth]{fig1.png}
\caption[my short caption]{Long caption }
\legend{some text}
\end{figure}


while the original (and invalid) latex output with the default latex export mechanism is:

\begin{figure}[htbp]
\centering
\includegraphics[angle=45,width=.9\linewidth]{fig1.png}
\caption[my short caption]{Long caption \legend{some text}}


Well, this part is working fine. However, my export-filter is also changing all other lines ending with }} and not only the caption ones...

This is the code of my export-filter:

  (require 'ox)
(defun my-filter (contents backend info)
(when (eq backend 'latex)
(replace-regexp-in-string "}}$" "}" (replace-regexp-in-string "\\\\legend" "}\n\\\\legend" contents)))) (add-to-list 'org-export-filter-final-output-functions #'my-filter)  Where is the mistake? • Well, that's exactly what you wrote: replace the legend stuff in contents and then replace }}$ by a single }. In shell terms, you've written echo $contents | sed 's/legend stuff/other legend stuff/' | sed 's/}}$/}/'. That final sed matches every line that ends in two braces. – NickD Nov 20 at 20:34
• well, I intend to replace the }} only in lines that match legend, but I am not sure if replace-regexp-in-string is applied by lines or in the entire text. – GP. Nov 21 at 9:00
• It is applied to the whole string. – NickD Nov 21 at 16:18