Skip to content

Instantly share code, notes, and snippets.

@simonecesano
Created May 9, 2023 07:19
Show Gist options
  • Save simonecesano/0e8fb3a234f60c512e19be830d9bbc27 to your computer and use it in GitHub Desktop.
Save simonecesano/0e8fb3a234f60c512e19be830d9bbc27 to your computer and use it in GitHub Desktop.
(defun replace-newlines-with-spaces ()
"Replace all newlines in the current region with spaces."
(interactive)
(save-excursion
(let ((start (if (region-active-p) (region-beginning) (point-min)))
(end (if (region-active-p) (region-end) (point-max))))
(goto-char start)
(while (search-forward "\n" end t)
(replace-match " " nil t)))))
(defun replace-multiple-spaces-with-single-space (beg end)
"Replace all occurrences of multiple spaces or tabs with a single space in the selected region."
(interactive "r")
(save-excursion
(goto-char beg)
(while (re-search-forward "[ \t]+" end t)
(replace-match " " nil nil))))
(defun replace-multiple-spaces-with-single-space (beg end)
"Replace all occurrences of multiple spaces with a single space in the selected region."
(interactive "r")
(save-excursion
;; Get the text of the region
(let ((text (buffer-substring-no-properties beg end)))
;; Replace multiple spaces with a single one
(setq text (replace-regexp-in-string "[ \t]+" " " text))
;; this is a bit of a mess:
;; (setq text (replace-regexp-in-string "\\(^\\|[^\n]\\)[ \t]+\\($\\|[^\n]\\)" " " text))
;; Replace the region's text with the modified text
(delete-region beg end)
(goto-char beg)
(insert text)
;; Adjust the region's boundaries to match the original text
(setq end (+ beg (length text)))
(set-mark end))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment