branch: externals/ellama
commit 07b4597b856b719f73cf9374fbd1aa0bf38f35bd
Merge: 1e1db6d5f1 4b053d3ccc
Author: Sergey Kostyaev <s-kosty...@users.noreply.github.com>
Commit: GitHub <nore...@github.com>

    Merge pull request #120 from s-kostyaev/fix-bad-code-blocks
    
    Fix bad code blocks during md to org conversion
---
 ellama.el            | 12 ++++++++++++
 tests/test-ellama.el | 28 ++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+)

diff --git a/ellama.el b/ellama.el
index 2af93a84e3..c10b8e4073 100644
--- a/ellama.el
+++ b/ellama.el
@@ -374,6 +374,17 @@ Too low value can break generated code by splitting long 
comment lines."
       (replace-regexp-in-string "^[[:space:]]*```\\(\\(.\\|\n\\)*\\)" 
"#+BEGIN_SRC\\1" text)
     text))
 
+(defun ellama--replace-bad-code-blocks (text)
+  "Replace code src blocks in TEXT."
+  (with-temp-buffer
+    (insert text)
+    (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)
+      (replace-match "#+BEGIN_SRC\\1#+END_SRC"))
+    (buffer-substring-no-properties (point-min) (point-max))))
+
 (defun ellama--translate-markdown-to-org-filter (text)
   "Filter to translate code blocks from markdown syntax to org syntax in TEXT.
 This filter contains only subset of markdown syntax to be good enough."
@@ -386,6 +397,7 @@ This filter contains only subset of markdown syntax to be 
good enough."
     (replace-regexp-in-string "^[[:space:]]*```$" "#+END_SRC")
     (replace-regexp-in-string "^[[:space:]]*```" "#+END_SRC\n")
     (replace-regexp-in-string "```" "\n#+END_SRC\n")
+    (ellama--replace-bad-code-blocks)
     ;; lists
     (replace-regexp-in-string "^\\* " "+ ")
     ;; bold
diff --git a/tests/test-ellama.el b/tests/test-ellama.el
index 7c7ffc03ee..384d8a418f 100644
--- a/tests/test-ellama.el
+++ b/tests/test-ellama.el
@@ -176,6 +176,34 @@ This code will create a rectangle with a blue border and 
light
 blue filling. You can replace \'Text\' with your desired text or other TikZ
 elements."))))
 
+(ert-deftest test-ellama-md-to-org-code-multiple-bad-blocks ()
+  (let ((result (ellama--translate-markdown-to-org-filter "Some text:
+```
+First block
+```
+other text:
+```
+Second block
+```
+more text:
+```
+third block
+```
+That's it.")))
+    (should (string-equal result "Some text:
+#+BEGIN_SRC
+First block
+#+END_SRC
+other text:
+#+BEGIN_SRC
+Second block
+#+END_SRC
+more text:
+#+BEGIN_SRC
+third block
+#+END_SRC
+That's it."))))
+
 (provide 'test-ellama)
 
 ;;; test-ellama.el ends here

Reply via email to