On 16/10/2022 23:33, Juan Manuel Macías wrote:
               (replace-regexp-in-string
                "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
                (replace-regexp-in-string
                 "\\(\\\\\\\\\n\\)+\\([ \t]*\\\\\\\\\\)+" "\n"
                 (replace-regexp-in-string
                  "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
                  (setq contents
                        (if lin
                            (replace-regexp-in-string "\\(\n\\)+\\([ \t]*\n\\)+" 
"\\\\\\\\!\n\n"
                                                      contents)
                          contents)) nil t) nil t) nil t) linreset)

I had a hope, it is possible to do it in a single pass of `replace-regexp-in-string', but unfortunately the function does not allow to make conditional substitution based on (rx (optional (group string-start))) (a bug?).

I still prefer to avoid replacement of latex newlines back to empty string. Though I am really happy with the following code, I expected a more concise snippet. Unit tests may found bugs in it.

(let ((contents "\n\n 0  \n\n\na b\nc d e  \n\n\nf g  \n   h i\n\n"))
  ;; Strip leading newlines.
  (setq contents
        (replace-regexp-in-string
         (rx string-start (1+ (0+ blank) ?\n)) ""
         contents 'fixed-case 'literal))
  ;; Add explicit line breaks and strip trailing spaces.
  (setq contents
        (replace-regexp-in-string
         (rx (0+ blank) ?\n
             (optional (group (1+ (0+ blank) ?\n)))
             (optional (group (0+ blank) (not (any blank ?\n)))))
         (lambda (m)
           (let ((par (match-string 1 m))
                 (next (match-string 2 m)))
             (if next
                 (concat (if par "\n\n" "\\\\\n")
                         next)
               "")))
         contents 'fixed-case 'literal))
  ;; Indented lines.
  (replace-regexp-in-string
   (rx line-start (1+ blank))
   (lambda (m) (format "\\hspace*{%dem}" (length m)))
   contents 'fixed-case 'literal))

Feel free to use it for inspiration during your work on a patch.


Reply via email to