字符gbk转换为utf-8的sublime插件

来源:互联网 发布:ubuntu wine qq2014 编辑:程序博客网 时间:2024/05/18 02:26
参照这里的文章http://www.sublimetext.com/forum/viewtopic.php?f=5&p=22274

一、点击菜单Tools -> New Plugin...,在创建好的py文件输入下列内容:
# Created by wofeiwo <wofeiwo#gmail.com> on 2011-09-07.
import sublime, sublime_plugin
import codecs

# Add "convert_coder_list" list in user settings,
# Or you can just modify your own charsets here.
DEFAULT_CODER = ["gb18030", "gbk", "gb2312", "big5", "utf-8", "utf-16le"]

class ConvertToUtf8Command(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view

        if view.is_loading():
            sublime.status_message("Waiting to loading.")
            return False
        
        coders = view.settings().get("convert_coder_list", DEFAULT_CODER)

        text = ""

        # Try to convert every coder in the list.
        for coder in coders:
                try:
                    theFile = codecs.open(view.file_name(),"r",coder)
                    text = theFile.read()
                    if len(text) != 0:
                        break
                except:
                    continue        
        
        # Replace all file content with new encoding data.
        view.run_command("select_all")
        view.replace(edit, view.sel()[0], text)

        # Reset cursor position.
        view.sel().clear()
        view.sel().add(sublime.Region(0))

    def is_enabled(self):
        return self.view.file_name() and len(self.view.file_name()) > 0


上述文件保存为convert_to_utf8.py
二、接下来,为刚才的插件分配快捷键。点菜单Tools -> Command Palette...,或者shift+cmd+p,打开命令集,选择“key Bindings - User”打开个人快捷键配置,输入下列内容:
    { "keys": ["ctrl+shift+c"], "command": "convert_to_utf8" } 




现在,使用ctrl+shift+c就可以把文件从gbk保存为utf-8格式的文件了。
PS:记得以前还用过一个install package的包,那个也好用,公司网络不行只好先用方案顶替一下了。