Removing extra whitespaces on bunch of PHP files using Ack-grep and Emacs

As a follow up to my own post on Indentations: Tabs vs. Spaces, I wanted to cleanup a number of files that contained a lot of extra and useless whitespaces that were getting on my nerves.

I did not want to spend too much time on this so, here is what I did.

First, here is what I have in my .emacs files that is needed for this to work:

(require 'whitespace)
(setq-default global-whitespace-mode t)
(setq-default whitespace-modes (quote (php-mode c-mode)))
(setq whitespace-style (quote (indentation::space trailing lines-tail)))

Then I used ack-grep (you can use find . -name '*.php' -exec) and xargs with emacs to clean it all up:

ack -f --php project/lib | xargs -L1 -I{} emacs -q -batch {} -eval '(progn(load-file "~/.emacs")(php-mode)(setq c-basic-offset 4)(whitespace-cleanup)(save-buffer))'

Here is the explanation:

ack -f --php project/lib

Finds all files endind with .php .phpt .php3 .php4 .php5 or .phtml (or more if you set it up) and print the file names from the project/lib folder.

| xargs -L1 -I{}

For every file outputed by ack, one by one execute the command (see below) and replace {} with the filename you get.

emacs -q -batch {}

The command being executed is emacs which is told NOT to load any init files but run a command in a batch mode (does not start the full editor).

-eval '(progn(load-file "~/.emacs")(php-mode)(whitespace-cleanup)(save-buffer))'

The emacs command being executed is in fact a set of commands. The first one is to load my .emacs files, then enter in php-mode, remove all the whitespaces and saves the file.

DONE

References:

I can ask you?

It is remarkable, very useful message

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • You may post PHP code. You should include <?php ?> tags.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options