sublime text3插件开发例程

github

sublime使用python编写插件,安装好sublime后,就自带了2个库sublime,sublime_plugin,基于这2个库,我们可以开发许多插件,以下就是一个简单的入门实例。

API介绍在https://www.sublimetext.com/docs/3/api_reference.html

官方教程在https://code.tutsplus.com/tutorials/how-to-create-a-sublime-text-2-plugin--net-22685

1.推荐一个截图软件Snipaste

2.打开tools->developer->new plugin

sublime text3插件开发例程_第1张图片

3.保存生成的文件xxx.py到Packages下,新建一个文件夹,自定义名称。

sublime text3插件开发例程_第2张图片

4.sublime会搜索packages下的py文件,用ctrl  + `  打开控制面板。输入view.run_command('example'),就可以看到文本中首行插入了Hello, World!,即执行了  self.view.insert(edit, 0, "Hello, World!")

sublime text3插件开发例程_第3张图片

5.Example就是这个类class的名称,用run command运行它的时候,就执行run这个函数下的指令(大概是这个意思)。一个py文件下可以有多个class,1个class下只有1个run入口。其他教程也有说明,Command前面的字段是命令名称,按大写字母分段,调用时都使用小写。

6.self.view.insert(edit, 0, "Hello, World!")     在API手册中看到,

insert(edit, point, string) int Inserts the given string in the buffer at the specified point. Returns the number of characters inserted: this may be different if tabs are being translated into spaces in the current buffer.

在指定point的位置插入后面string。

7.接下来我要实现在文本中选中一段注释改变成下面这个样式。右键点击快捷方式,或按ctrl + 1 插入分割线。如下图的效果。

sublime text3插件开发例程_第4张图片

8.首先要找到当前光标的位置,取出要的字符串,插入cutline,将字符串插入进去。

import sublime
import sublime_plugin
import re
import math

class AddcutlineCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		region = self.view.sel()[0]       #获取当前选取的区域,a = self.view.sel()[0].a 获取当前区域的起始point 
		str_a = self.view.substr(region)  #获取当前选择区域字符串
		parameter = sublime.load_settings("AddCutLine.sublime-settings")
		LEN = parameter.get('LEN')
		print(LEN)
		if len(str_a)==0:                 #如果仅是光标的位置,从该位置的那一行顶行插入cutline
			region=self.view.line(region) #获取从行开始的region
			point = region.a
			if LEN == "long":
				self.view.insert(edit, point, "//=======================================================================================================================================================\n")      #打印时显示在最底下
				self.view.insert(edit, point, "//---------------------------------------------------------------------- Text Here ----------------------------------------------------------------------\n")
				self.view.insert(edit, point, "//=======================================================================================================================================================\n") 
			elif LEN == "short":
				self.view.insert(edit, point, "//===========================================================================\n")      #打印时显示在最底下
				self.view.insert(edit, point, "//-------------------------------- Text Here --------------------------------\n")
				self.view.insert(edit, point, "//===========================================================================\n")
		else:
			print(str_a)
			region=self.view.line(region)
			point = region.a
			print(region)
			str_a = self.view.substr(region)
			print(str_a)
			str = re.findall(r"[/#]+\s*(.*\S+)\s*$", str_a)  #取得//或者#后面的字符串,去除前后空格
			srt_len =len(str[0]) 
			print(srt_len)
			print(str)

			if LEN == "short":
				self.view.erase(edit,region)
				self.view.insert(edit, point, "//===========================================================================\n")      #打印时显示在最底下
				self.view.insert(edit, point, "//---------------------------------------------------------------------------\n")
				self.view.insert(edit, point, "//===========================================================================\n")
	
				first_line_end = self.view.line(point).b #获取当前行的region (1739, 1816) 起始point
	
				print(first_line_end)
				#计算替换字符串的偏移量
				start_p = first_line_end+round((75-srt_len)/2)+3
				r1 = sublime.Region(start_p,start_p+srt_len) 
				print(round((75-srt_len)/2))
				self.view.replace(edit, r1, str[0])           #将该区域替换为原来的注释
			elif LEN == "long":
				self.view.erase(edit,region)
				self.view.insert(edit, point, "//=======================================================================================================================================================\n")      #打印时显示在最底下
				self.view.insert(edit, point, "//-------------------------------------------------------------------------------------------------------------------------------------------------------\n")
				self.view.insert(edit, point, "//=======================================================================================================================================================\n") 
	
				first_line_end = self.view.line(point).b #获取当前行的region (1739, 1816) 起始point
	
				print(first_line_end)
				#计算替换字符串的偏移量
				start_p = first_line_end+round((151-srt_len)/2)+3
				r1 = sublime.Region(start_p,start_p+srt_len) 
				print(round((151-srt_len)/2))
				self.view.replace(edit, r1, str[0])           #将该区域替换为原来的注释

9.代码编写完成后,设置快捷键和文本右键快捷方式。拷贝其他插件的2个文件到py目录。

sublime text3插件开发例程_第5张图片

Context.sublime-menu是在文本编辑界面中的右键菜单,keymap是设置快捷键的。还是side bar是设置右边文件栏的右键菜单,还没有搞过,原理一样的。

Context.sublime-menu:

[
	{ "caption": "-", "id": "addcutline" },  //再建一个右键菜单中的分段。可以没有。id是唯一标识
	{ "command": "addcutline", "caption": "AddCutLine" },    //command就是具体要执行的命令,caption是显示的名称
]

Default (Windows).sublime-keymap:

[
	{ "keys": ["ctrl+1"], "command": "addcutline"},
]

AddCutLine.sublime-settings:   设置参数,在py文件中可以引用里面的设置

{
	//long or short
	"LEN":"short"

}

Main.sublime-menu:在主菜单中显示相关设置和read me信息。

[
	{
		"caption": "Preferences",
		"mnemonic": "n",
		"id": "preferences",
		"children":
		[
			{
				"caption": "Package Settings",
				"mnemonic": "P",
				"id": "package-settings",
				"children":
				[
					{
						"caption": "AddCutLine",
						"children":
						[
							{
								"command": "open_file",
								"args": {"file": "${packages}/AddCutLine/README.md"},
								"caption": "README"
							},
							{ "caption": "-" },
							{
								"caption": "Settings",
								"command": "edit_settings",
								"args": {
									"base_file": "${packages}/AddCutLine/AddCutLine.sublime-settings"
								}
							}
						]
					}
				]
			}
		]
	}
]
//===========================================================================
//----------------------------------Read Me----------------------------------
//===========================================================================


#选择一行已经被//或者#注释的语句,右键选择AddCutLine或者Ctrl+1快捷键,会快速将该注释格式化成上面 Read Me所示。
#注意,如果有中文,中间的右侧会多出来一些。

以上操作后,完整的一个插件就诞生了。有关python和正则表达式的学习请同学们移步其他教程,本文简单介绍如何编写sublime text3的插件。

sublime text3插件开发例程_第6张图片

sublime text3插件开发例程_第7张图片

//===========================================================================
//----------------------------------Thanks-----------------------------------
//===========================================================================

以此文感谢niechuan老师在我python和正则表达式前行路上的帮助,祝nie老师永垂不朽!

 

 

 

你可能感兴趣的:(sublime)