python 写的javascript格式化程序

    最近用python语言写了一个js格式化文件,支持 单个文件或者目录下所有js文件的格式化,功能还行.算法的思想来自于Einar Lielmanis,详见http://jsbeautifier.org/

     这个程序花了我几天的时间,熬了几个晚上,加上感冒,几次想放弃...所以写下来,纪念下.截取部分代码如下:

代码一:

    while (True) :
        token_text, token_type= get_next_token()
        if (token_type == 'TK_EOF') :
            break
        eval("proc_"+token_type)()

        constants.last_last_text = constants.last_text
        constants.last_type = token_type
        constants.last_text = token_text

    return re.sub(r"[\n]+$","",''.join(constants.output))

代码二:

def proc_TK_START_BLOCK():
        if (constants.last_word == 'do') :
            set_mode('DO_BLOCK')
        else :
            set_mode('BLOCK')

        if (constants.last_type == 'TK_OPERATOR' and constants.last_type == 'TK_START_EXPR') :
            if (constants.last_type == 'TK_START_BLOCK') :
                print_newline()
            else :
                print_single_space()
        indent()
        print_token()

代码三:

    def proc_TK_END_BLOCK():
        #pdb.set_trace()
        restore_mode()
        if (constants.last_type == 'TK_START_BLOCK') :
            # nothing
            if (constants.just_added_newline) :

                remove_indent()
            else :
                trim_output()
        else :
            print_newline()
        print_token()

最后提供一个可执行程序的下载:

http://files.cnblogs.com/ms_config/dist.rar

源程序:

http://files.cnblogs.com/ms_config/python_js_beautiful_source.rar

posted on 2010-03-16 16:25 叶子绿 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/ms_config/archive/2010/03/16/1687403.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值