Emacs is an excellent editor. (Please note, I don’t want to make any comments on VIM here.) But, Emacs can also be used as a command line tool. Here is one of the uses of Emacs as a command line tool, to remove tabs from a source file.

Removing tabs and replace with white spaces

Windows

1emacs.exe -batch <filename> -l "%appdata%\.emacs" -f mark-whole-buffer -f untabify -f whitespace-cleanup -f save-buffer -kill

Linux

1emacs -batch <filename> -l "~/.emacs" -f mark-whole-buffer -f untabify -f whitespace-cleanup -f save-buffer -kill

Here, replace <filename> with your file.

Command line parameters

Let’s explain all the parameters.

emacs.exe / emacs
The executable
-batch
Run emacs in batch mode
<filename>
The file where we want to operate on
-l "%appdata%\.emacs"
On windows, this is the default location of emacs’s own configuration file.
-l "~/.emacs"
This is the default location of emacs’s configuration file on linux.
-f mark-whole-buffer
Selected everything from <filename>
-f untabify
Remove tabs from that file
-f whitespace-cleanup
Remove trailing spaces, etc.
-f save-buffer
Save the modified file
-kill
Exit emacs

Installing Emacs

Installing Emacs on Windows

Download latest version from http://ftpmirror.gnu.org/emacs/windows/. As of writing of this post, http://ftpmirror.gnu.org/emacs/windows/emacs-26/ has pre-compiled binaries for the latest version.

NOTE: The root folder of http://ftpmirror.gnu.org/emacs/windows/ has source files, which are helpful only if you plan to compile emacs on your own.

Installing Emacs on Linux

Run familiar code for your Linux distribution.

1sudo apt-get install emacs

Configure Emacs

In your %appdata%\.emacs, or ~/.emacs, ensure you have

1  (custom-set-variables
2    ;; ...
3    '(indent-tabs-mode nil) ; Do not insert tabs
4    '(tab-width 4)          ; Tab is by default of 4 spaces
5   )

This step is needed for emacs. Default settings will insert tabs.

Why do we do it?

Different projects have different coding styles in their projects. Either with tabs, with spaces, tabs width of 4, or 8, but a decent maintained project does have such conventions.

If you blindly just replace “\t” with “4” or “8” spaces, the result would be ugly. You need some intelligence in the tool to do this neatly. This intelligence is what Emacs has.

With “\t” for tabs

Assuming we have a source file with such tabs.

1int x\t=\t1;
2int xy\t=\t1;
3int xyz\t=\t1;

Blind replace 4

If we blindly replace tabs with 4 spaces

1int x    =    1;
2int xy    =    1;
3int xyz    =    1;

Blind replace 8

If we blindly replace tabs with 8 spaces

1int x        =        1;
2int xy        =        1;
3int xyz        =        1;

Neatly replace 4

If we use emacs to replace tabs with 4 spaces

1int x   =    1;
2int xy  =    1;
3int xyz =    1; /* Replaced tab by just 1 space */

Neatly replace 8

If we use emacs to replace tabs with 8 spaces

1int x       =        1;
2int xy      =        1;
3int xyz     =        1;