Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to collapse whitespaces in a region?

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
like image 489
user525602 Avatar asked Dec 30 '11 00:12

user525602


2 Answers

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))
like image 189
Trey Jackson Avatar answered Oct 13 '22 03:10

Trey Jackson


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.

like image 15
Sivaram Avatar answered Oct 13 '22 05:10

Sivaram