Let's say I have this tabulated text file:
field1 variable_length_field variable_length_field
aaaaaa aaaa aaaaaaaaa
bbbbbb bbbbbbbbbbbbbbbbbbbb bbbb
How can I transform it to:
field1 variable_length_field variable_length_field
aaaaaa aaaa aaaaaaaaa
bbbbbb bbbbbbbbbbbbbbbbbbbb bbbb
I know I could use replace-regexp
on the region, but Emacs regexps don't come naturally. I was looking for something like delete-whitespace-rectangle
, but that does not do what I expect, or I am misusing it. Having the ability to do this per-column would be desirable too, i.e:
field1 variable_length_field variable_length_field
aaaaaa aaaa aaaaaaaaa
bbbbbb bbbbbbbbbbbbbbbbbbbb bbbb
This function should do the trick:
(defun just-one-space-in-region (beg end)
"replace all whitespace in the region with single spaces"
(interactive "r")
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(while (re-search-forward "\\s-+" nil t)
(replace-match " ")))))
And, since the question was updated to apply to spaces in a rectangle, try this:
(require 'rect)
(defun just-one-space-in-rect-line (start end)
(save-restriction
(save-match-data
(narrow-to-region (+ (point) start)
(+ (point) end))
(while (re-search-forward "\\s-+" nil t)
(replace-match " ")))))
(defun just-one-space-in-rect (start end)
"replace all whitespace in the rectangle with single spaces"
(interactive "r")
(apply-on-rectangle 'just-one-space-in-rect-line start end))
Not really answering your question but there is
M-SPC runs the command just-one-space, which is an interactive
compiled Lisp function in `simple.el'.
It is bound to M-SPC.
(just-one-space &optional N)
Delete all spaces and tabs around point, leaving one space (or N spaces).
[back]
which is useful when you want to delete whitespace in one off cases. It might be suitable for a macro case where the deletions are at random lines with no fixed pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With