Last active
July 15, 2022 23:11
-
-
Save haji-ali/3d8f4c28e21866e11a87b3e27476ad1c to your computer and use it in GitHub Desktop.
Break long string with backslashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun break-string (do-not-break column-width) | |
"Break string to a fit within a fill-column. | |
If DO-NOT-BREAK is non-nil (set with `C-u') then join a broken | |
string. COLUMN-WIDTH defaults to `fill-column'" | |
(interactive (list current-prefix-arg | |
fill-column)) | |
(save-excursion | |
(let* ((initial (point)) | |
(string-start (search-backward-regexp "\\([^\\]\\|^\\)\"" nil t)) | |
(start-col (current-column)) | |
(string-end (progn | |
(forward-char) | |
(search-forward-regexp "[^\\]\"" nil t))) | |
prev-pos next-pos) | |
(unless (and string-start string-end | |
(<= string-start initial) | |
(>= string-end initial)) | |
(error "Cannot find string limits.")) | |
(goto-char (+ string-start (if (looking-at "\"") 1 2))) | |
(while (search-forward-regexp "\\(\n\\|\"\\)" string-end t) | |
(setq next-pos (match-end 0)) | |
(goto-char (match-beginning 0)) | |
(if (and (not do-not-break) | |
(> (current-column) column-width)) | |
(progn | |
(goto-char (+ string-start (- column-width start-col))) | |
(insert "\\\n") | |
(setq start-col (current-column)) | |
(setq string-start (point)) | |
(setq string-end (+ string-end 2))) | |
(if (and (progn (backward-char) | |
(looking-at "\\\\\n")) | |
(or do-not-break | |
(< (current-column) column-width))) | |
(progn (delete-char 2) | |
(setq string-end (- string-end 2))) | |
(setq start-col (current-column)) | |
(setq string-start (point)) | |
(goto-char next-pos))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment