branch: externals/ellama
commit 2f16b6be2e8afdff5e30505b91e237c45ffe4e4c
Author: Sergey Kostyaev <[email protected]>
Commit: Sergey Kostyaev <[email protected]>

    Fix bad src block replacement nil match crash
---
 ellama.el            | 23 ++++++++++++-----------
 tests/test-ellama.el |  4 ++++
 2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/ellama.el b/ellama.el
index 33788ab268..a6c07d7496 100644
--- a/ellama.el
+++ b/ellama.el
@@ -568,17 +568,18 @@ It should be a function with single argument generated 
text string."
   "Replace code src blocks in TEXT."
   (with-temp-buffer
     (insert (propertize text 'hard t))
-    (goto-char (point-min))
-    ;; skip good code blocks
-    (while (re-search-forward "#\\+BEGIN_SRC\\(.\\|\n\\)*?#\\+END_SRC" nil t))
-    (while (re-search-forward "#\\+END_SRC\\(\\(.\\|\n\\)*?\\)#\\+END_SRC" nil 
t)
-      (unless (string-match-p "#\\+BEGIN_SRC" (match-string 1))
-       (replace-match "#+BEGIN_SRC\\1#+END_SRC")))
-    (goto-char (match-beginning 0))
-    (while (re-search-backward "#\\+END_SRC\\(\\(.\\|\n\\)*?\\)#\\+END_SRC" 
nil t)
-      (unless (string-match-p "#\\+BEGIN_SRC" (match-string 1))
-       (replace-match "#+BEGIN_SRC\\1#+END_SRC"))
-      (goto-char (match-beginning 0)))
+    (let ((open-blocks 0)
+          (pattern
+           
"^\\([[:blank:]]*\\)#\\+\\(BEGIN_SRC\\|END_SRC\\)\\(?:[[:blank:]].*\\)?$"))
+      (goto-char (point-min))
+      (while (re-search-forward pattern nil t)
+        (if (string= (match-string 2) "BEGIN_SRC")
+            (setq open-blocks (1+ open-blocks))
+          (if (> open-blocks 0)
+              (setq open-blocks (1- open-blocks))
+            (let ((indent (match-string 1)))
+              (replace-match (concat indent "#+BEGIN_SRC") t t))
+            (setq open-blocks (1+ open-blocks))))))
     (buffer-substring-no-properties (point-min) (point-max))))
 
 (defun ellama--replace (from to beg end)
diff --git a/tests/test-ellama.el b/tests/test-ellama.el
index b81c5f5ba4..375e06abff 100644
--- a/tests/test-ellama.el
+++ b/tests/test-ellama.el
@@ -842,6 +842,10 @@ That's it."))))
     (should (string-match-p "#\\+END_SRC" result))
     (should (string-match-p "#\\+END_QUOTE" result))))
 
+(ert-deftest test-ellama-replace-bad-code-blocks-no-src-blocks ()
+  (let ((text "\n#+BEGIN_QUOTE\n((shell_command . ))\n#+END_QUOTE\n"))
+    (should (string-equal (ellama--replace-bad-code-blocks text) text))))
+
 (ert-deftest test-ellama-md-to-org-code-inline-latex ()
   (let ((result (ellama--translate-markdown-to-org-filter "_some italic_
 $$P_\\theta(Y_T, ..., Y_2|Y_1, x_1, ..., x_T)$$

Reply via email to