[TxMt] How to open an encoded file with TextMate?

Hans-Joerg Bibiko bibiko at eva.mpg.de
Fri Oct 13 19:06:20 UTC 2006

Many users mentioned that there is sometimes the need to open a file  
which is encoded in e.g. Chinese Big5 or in Japanese Shift-JIS.
The TextMate manual recommends in respect to that topic to use the  
UNIX command 'iconv'. It works perfectly, but if you have to open many  
files of different encodings the typing of such commands will become a  
bit uncomfortable.

To make it a bit easier I wrote with the Bundle Editor a new template  
called openEncodedFile based on CocoaDialog's features.

Here is one way to use my suggestion:

- open the Bundle Editor
- Show all
- go to the folder 'TextMate' (or whatever)
- add a new template 'openEncodedFile' (or whatever)
Template data
- Extension: leave it empty
- Command(s):

# open CocoaDialog's file select menu
file=$(CocoaDialog fileselect \
	--title "Open an encoded file" \
	--with-directory $HOME/ \
# check for valid file
if [ -n "$file" ]; then
# open CocoaDialog's dropdown menu
# for more encodings add them to '--items'
# to list all possibile encodings use the Terminal with 'iconv -l'
	res=$(CocoaDialog dropdown \
		--title "Open an encoded file" \
		--text "Choose the encoding:" \
		??exit?onchange \
		--button1 "Open" \
		--button2 "Cancel" \
		--items "BIG5" "EUC-TW" "GB2312" "SJIS" "EUC-JP" "KOI8-R" \
# if user canceled exit
	[[ $( (tail -r <<<"$res") | tail -n1)  == "2" ]] && \
	res=$(tail -n1 <<<"$res")
# add more 'elif' according to '--items' if needed
	if [ "$res" == 0 ]; then
	elif [ "$res" == 1 ]; then
	elif [ "$res" == 2 ]; then
	elif [ "$res" == 3 ]; then
	elif [ "$res" == 4 ]; then
	elif [ "$res" == 5 ]; then
# start conversion to UTF-8 and send the result as a new file back to TM
	iconv -f "$ENC" -t utf-8 "$file" > "$TM_NEW_FILE"

- Output: Insert as Text
- Activation: Key Equivalent shift+option+o (my suggestion)
- Scope: leave it empty

I've chosen a new template because the used keyboard short-cut is also  
available if no document is open.

As you can see in the script you can add/edit encodings very easily.  
(More details within the code)

If you start that bundle (shift+option+o) you will see a file choose  
menu. Select your file and press ENTER or 'Open'. Then you will be  
asked to input the right encoding. The available encodings are listed  
in a drop-down menu. Select one encoding and press ENTER or 'Open'.  
The script will convert your file according to the selected encoding  
to utf-8. The result will be shown in a new document.

Hopefully the very tiny script is useful for others as well. Feedback  
is highly welcomed.

Many greetings,

Hans-Jörg Bibiko

PS TODO: Include an automatical encoding detection. Hopefully coming soon ;)

This message was sent using IMP, the Internet Messaging Program.

More information about the textmate mailing list