Thursday, October 17, 2013

Convert Spaces to Tabs in one whack

Working with CoffeeScript is a pleasure.

It is easy to create beautiful CoffeeScript code since blocks are determined by indentation.

However, that can be a two edged sword.

If you mix your SPACES with TABs, which can be easy to do in a team development environment, you are in for a world of hurt.

Fortunately, there are techniques for dealing with this TAB/SPACE issue.

Here are a few things I configure in my IDE for working with CoffeeScript files:
  • Use TAB characters instead of SPACES
  • 3 characters per TAB
  • Show Whitespaces

For non CoffeeScript files

For all other file types (not CoffeeScript) I use SPACES
  • Use SPACES for TABs
  • 3 characters (spaces) per TAB
  • Do not show Whitespaces

The reason for using SPACEs, e.g., for Ruby files, is because when copy/pasting from IDE to console you'll often get errors when using TABs.

Bash script used by find command

When I have a number of files that have spaces in them, here's how a convert the lot of them from SPACES to TABs:

unexpand_cmd


FILENAME=$1
CURRENT_PROCESS_NAME=$$
TMP_FILENAME="/tmp/$(basename $0).$CURRENT_PROCESS_NAME.tmp"
if [ -z $FILENAME ]; then
 echo "Usage:  unexpand_cmd "
 exit 1
fi
unexpand -t 3 $FILENAME > $TMP_FILENAME && cat $TMP_FILENAME > $FILENAME && rm $TMP_FILENAME

Word of caution

This assumes that the source files use units of 3 spaces for indentation.

If your source files use other units, you should replace the "3" with what ever unit your files use.

Set the execute bit


$ chmod +x ./unexpand_cmd

p.s. You'll want to save this file in a directory that's on your path.
p.s.s. Since this modifies your source files, please make a full backup before running this.

Run find command and execute unexpand_cmd on each


$ find app/assets/javascripts -name "*js.coffee" -type f -exec unexpand_cmd {} \;

Notes

When you see "Soft Tabs" in your IDE preferences, that means "Use 3 spaces instead of 1 tab character", assuming you have set your tab to 3 spaces.

1 comment: