reddit / emacs

Unexpected behavior of replace-regexp-in-string with REP begin a function

Titikomba · 2022-09-21 09:18
Hi all, I'm currently trying to build a small package `org-inline-block` that aims to provide a simple syntax for blocks (without begin/end) based on indentation (like plain lists). While it would be cleaner to properly extend `org-element` for the export part, I only plan to add a function to '`org-export-filter-body-functions`. Here comes the function (simplified version that isolates the problem): (defun org-latex-inline-block (text backend info) "Manage inline block in LaTeX export, as part of body." (when (org-export-derived-backend-p backend 'latex) (let ((case-fold-search nil)) (replace-regexp-in-string "\\([ \t]*\\)\\(\\(Question\\)\\( (\\([^()]*\\))\\)?\\.\\)\\(\\(.*$\\)\\([\n]\\(\\1[\t ]+.*\\)?\\)*\\)" (lambda (substr) (format "\\begin{question}%s\\end{question}" (org-inline-block-get-core substr))) text nil t)))) with (defun org-inline-block-get-core (s) "Given >Question. abcde<, return >abcde<" (let ((case-fold-search nil)) (string-match "Question\\( ([^()]*)\\)?\\. " s) (if (> (match-end 0) 0) (substring s (match-end 0)) ""))) Here comes the unexpected behavior: if I try to export "Question. Where is Brian?", it will be exported to "\begin{question} Where is Brian? \end{question} **Where is Brian?** ", and I can't guess where this duplicate comes from... Any idea ?
7890yuiop · 2022-09-21 10:43
Much better, cheers. ---- ~~The only code block formatting method which [works for all users](https://reddithelp.com/hc/en-us/articles/360043033952-Formatting-Guide#wiki_code_blocks_and_inline_code) of reddit is to switch the reddit editor to markdown mode* and indent the code by 4 spaces (you can use `M-4 C-x C-i` on a region followed by `M-x untabify` to achieve this in Emacs); and you need to use empty lines to separate the indented lines from the other text. Otherwise for lots of readers your message looks like this: https://old.reddit.com/r/emacs/comments/xjzvwv/unexpected_behavior_of_replaceregexpinstring_with/~~ ~~Be sure to remove any different syntax intended for formatting (such as triple backticks) at the same time.~~ ~~(*) Switching to the markdown editor may or may not still be necessary. At one time it prevented problems.~~
Titikomba · 2022-09-21 10:57
Edited, thanks!
7890yuiop · 2022-09-21 11:43
You're clobbering (corrupting, to all intents and purposes) the match data in the middle of a function which uses it. You need to use `save-match-data` to restore the prior data: (defun org-inline-block-get-core (s) "Given >Question. abcde<, return >abcde<" (save-match-data (let ((case-fold-search nil)) (string-match "Question\\( ([^()]*)\\)?\\. " s) (if (> (match-end 0) 0) (substring s (match-end 0)) ""))))
Titikomba · 2022-09-21 13:53
That's it, thanks a lot!