Sublime Text 3 实现快捷键插入时间

写项目日志,需要记录下每次完成小模块的时间点,参照github上一位仁兄的插件,实现快捷键插入当前时间,链接如下:

https://github.com/kairyou/SublimeInsertDatetime

研究了一下代码,用的是python,具体思路是获取时间,也是蛮好理解的。

import sys, sublime_plugin, datetime

class insertDatetimeCommand(sublime_plugin.TextCommand):
  def run(self, edit, format):
    timestamp = datetime.datetime.now()
    if format == 'ymd':
        # yyyy-mm-dd
        timestamp = timestamp.strftime('%Y-%m-%d')
    elif format == 'ymdhms':
        # %X = %H:%M:%S
        timestamp = timestamp.strftime('%Y-%m-%d %X')
    else: # format == "xxx"
        # 2012-02-18 13:17:28.047000
        #timestamp = datetime.datetime.now().isoformat(' ')
        # Sat Feb 18 13:20:41 2012
        #timestamp = datetime.datetime.now().ctime()

        # 数字变为字符串 str(xx),字符串变为数字 int(string)
        timestamp = int(timestamp.strftime("%w"))
        week = {
            1 : '一', 2 : '二', 3 : '三', 4 : '四', 5 : '五', 6 : '六', 7 : '日'
        }

        timestamp = '星期' + week[timestamp]
        
        # print(sys.version_info[:2] < (3,0))
        if sys.version_info[:2] < (3,0):
            ## 中文要指定: coding=utf-8 | gbk ,再decode
            timestamp = timestamp.decode('utf-8')
        # else:
            # timestamp = timestamp.encode('utf-8').decode('utf-8')

    #for region in the selection
    for r in self.view.sel():
      #put in the timestamp
      #(if text is selected, it'll be replaced in an intuitive fashion)
      self.view.erase(edit, r)
      self.view.insert(edit, r.begin(), timestamp)

把文件保存在‘sublime\Data\Packages’目录下,然后在‘Preference → Key Bindings - User’中设置快捷键映射:

[
    { 
	    "keys": ["f5"], "command": "insert_datetime",
	    "args": {"format": "ymd"}
	},
	{ 
	    "keys": ["alt+f5"], "command": "insert_datetime",
	    "args": {"format": "ymdhms"}
	},
    {
	    "keys": ["ctrl+f5"], "command": "insert_datetime",
    	"args": {"format": "E"}
	}
]

重启Sublime即可。

你可能感兴趣的:(编辑器使用)