Sublime Text進階(二) API的使用:TextCommand

前言

在(一)中我們使用了 WindowCommand Class 里面的window.run_command去批量執(zhí)行了一堆命令,
在很長一段時間里都滿足了我的使用需求.比如批量預處理一些日志,預處理一些繁瑣但是工作內(nèi)容固定的任務(wù).
類似下面

import sublime
import sublime_plugin

class UsEditCommand(sublime_plugin.WindowCommand):
    def run(self, reverse=False):
        window = self.window
        window.run_command("show_panel", {"panel": "find"})#打開查找面板
        window.run_command("insert", {"characters": "[\(\)\{\}\$\^\-]"})#輸入字符串[\(\)\{\}\$\^\-]
        window.run_command("hide_panel",{"cancel":"true"})#關(guān)掉查找面板
        window.run_command("find_all", {"characters": "n"})#查找所有符合的內(nèi)容
        window.run_command("left_delete")#左刪除
#在Key Bindings 里面添加快捷鍵
#{ "keys": ["f5"], "command": "us_edit" }

上面代碼所做的工作其實是查找出所有 (){}$^- 這些符號刪掉,這里是輸入了一個正則表達式,而我們操作的時候,是需要先打開啟用正則表達式開關(guān)的,(因為沒有打開、關(guān)閉正則表達式的command)如果沒有打開的話,其實是在查找符合的字符串然后刪掉的,也就不符合我們的場景需求,即沒有效果了.

此外使用 window.run_command 去做一個批處理的操作還有一些其他的缺陷

  • 只能按照固定命令執(zhí)行,無法添加邏輯判斷等,不能處理一些復雜的文字處理
  • 如果使用到查找功能,需要手工開啟/關(guān)閉正則表達式功能
  • 如果執(zhí)行了不是我們想要的效果,撤退需要撤退多次(類似于你自己操作了那么多步驟,所以撤退還是要按多次的)
  • 雖然有大部分command,但還是不足夠我們使用

此篇文章介紹一下Sublime Text API 里面的Sublime.view 和TextCommand,已經(jīng)如何使用view 來創(chuàng)建一些自定義的Command.

sublime.View

TextCommand里面的View提供了更多操縱視圖的方法,如內(nèi)容的新增、修改、替換和光標的一些操作等.
那么如何使用view呢?我們先在User目錄下面先新建一個py文件

TestView.py

import sublime
import sublime_plugin
class TestViewCommand(sublime_plugin.TextCommand):
    def run(self,edit):
        view = self.view
        point =  view.sel()[0].begin()
        view.insert(edit,point,"hello Sublime Text")
#{ "keys": ["f5"], "command": "test_view" },

上面代碼的執(zhí)行效果是在你的當前視圖的第一個光標所在位置插入了 "hello Sublime Text" 內(nèi)容.觀察可以發(fā)現(xiàn)與上一章不一樣的是現(xiàn)在這里引用了TextCommand 替換了WindowCommand 且 run()里面添加多了一個edit參數(shù). edit 是TextCommand里面的一個對象,view里面對內(nèi)容操作的一些方法需要使用到TextCommand 的edit對象才可以編輯.

view相當于我們獲取當前所在的sublime的窗口的視圖,獲取了該視圖才能對里面的內(nèi)容做操作.

view一些常用的方法

    view.file_name()#獲取當前視圖的文件名(包含文件路徑)
    view.run_command()#等價于window.run_command()
    view.substr(region)#獲取此region區(qū)域的內(nèi)容
    view.substr(point)#獲取此point區(qū)域的內(nèi)容
    view.insert(edit, point, string)#在此point上插入字符串string
    view.replace(edit, region, string)#替換region上的內(nèi)容為string
    view.sel()#獲取當前光標所在的region,返回region的數(shù)組Selection.(因為光標可以多選)
    view.line(point)#獲取此point的所在行的region
    view.find(pattern, start_point, <flags>)#查找符合正則表達式pattern的內(nèi)容所在的Region,從start_point開始查找,返回第一個符合的Region
    view.find_all(pattern, <flags>, <format>, <extractions>)#同上,返回所有符合的Region

解釋view里面參數(shù)的含義

point = x 表示一個整數(shù),表示一個位置,從文本開頭計算,第一個為0,一個任意字符占用一個位置
reigon =(x,y) 表示一個區(qū)域,兩個point指間的內(nèi)容,表示第x個字符到第y個字符指間的區(qū)域
selection = [(x,y),(x1,y1),(x2,y2)],表示一組區(qū)域,如在多行編輯的時候 view.sel()就返回一組region

如果對point,region,selection有不太理解的話
可以試試下面代碼自己動手操作試試輸出是什么,更容易理解

import sublime
import sublime_plugin
class HelloWorldCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        selection = view.sel()
        if selection:
            print("selection = ",selection)#輸出Selection 對象 到console 面板
            for region in selection:
                print("region = ",region)#輸出region
                print("begin point = ",region.begin())#輸出region的第一個point

        str = view.substr(selection[0])#獲取第一個光標選中的內(nèi)容
        print("str = ",str)
        #輸出當前文件的路徑到光標位置上
        path = view.file_name()#獲取文件名(包含路徑)
        point =  view.sel()[0].begin()#獲取當前視圖第一個光標region的第一個位置
        view.insert(edit,point,path)#在此point上輸出file_name
#{ "keys": ["f5"], "command": "hello_world" },

一些例子

有時候我們經(jīng)常需要獲取當前文件目錄,那么可以使用下面代碼

import re
import sublime
import sublime_plugin
class GetPathCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        def getpath():
            pattern = re.compile(r"\\[\w._-]+$")
            return re.sub(pattern, '', view.file_name())
        view.insert(edit,view.sel()[0].begin(),getpath())
#{ "keys": ["f5"], "command": "get_path" },
#改寫一下可以講路徑存到剪貼板,可以當作練習
image
image

對選中的內(nèi)容中,替換為首字母大寫

import sublime
import sublime_plugin
class CamelCaseCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        selection = view.sel()
        for region in selection:
            str = view.substr(region)
            str = str.title()
            view.replace(edit,region,str)
#{ "keys": ["f5"], "command": "camel_case" },
image
image

在多個光標下輸入遞增數(shù)字

import sublime
import sublime_plugin
class MultiNumberCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        selection = view.sel()
        for i in range(0,len(selection)):
            view.insert(edit,selection[i].begin(),str(i))
#{ "keys": ["f5"], "command": "multi_number" },
image
image

此篇文章需要有一定python的基礎(chǔ)知識,python的基礎(chǔ)語法也不會太難,花幾個小時基本上就可以學會,我本人也不是學python的.有興趣的小伙伴可以周末花個半天學學python的基礎(chǔ)語法,再研究一下sublime Text的API,就可以寫一些自己想要的command了.

如果有幫助,請幫忙點喜歡,謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容