寫一個Sublime Text 2外掛程式(CSS檔案裡px單位替換成rem單位),sublimerem

來源:互聯網
上載者:User

寫一個Sublime Text 2外掛程式(CSS檔案裡px單位替換成rem單位),sublimerem
三年前我就知道了sublime text 不過那時候用DW還是很爽的樣子,後來有天想為難自己了,於是用了兩年的vim和五筆,最近又覺得這麼好編輯器也可以試試,改變一下自己,用一下的,不過由於工作的原因,沒有堅持下來,有時候順手似乎比先進更重要一些。最近工作都是做一些移動端的頁面,而的長按出現二維碼有個bug,在ios裡縮放的頁面長按是不會出現“識別二維碼”的。所以需要轉換一下,不要讓頁面縮放,要自適應,這個時候就用rem單位來做的會比較好一些,而我的同事之前開發了一個px to  rem的工具https://github.com/stormtea123/viewtorem。用他的工具就可以搞定的。奈何我這等懶人,把這個工具給到別人還要和別人說的,覺得累。於是就想寫個sublime text 外掛程式算了。很簡單的一個需求:找到CSS檔案裡px單位改成rem單位。第一步搜百度凡事問百度,結果全是 How to Create a Sublime Text 2 Plugin 這篇文章的翻譯,還不全,不會英語的要哭倒了。當然也有一些收穫:Sublime Text 介面的中文文檔 http://www.oschina.net/translate/sublime-text-plugin-api-reference 和 英文文檔:http://www.sublimetext.com/docs/2/api_reference.html 。沒有想到這個編輯器不同的版本借口命名還有差異,頂,好吧,不會的地方記得要看英文的。第二步設定外掛程式先找到外掛程式的目錄,通過Tools -> New Plugin...來開啟一個初始化的外掛程式編輯檔案,它會有這樣的內容:

import sublime, sublime_pluginclass ExampleCommand(sublime_plugin.TextCommand):     def run(self, edit):          self.view.insert(edit, 0, "Hello, World!")

然後Ctrl+s,來儲存這個檔案,這個時候電腦就會開啟到要儲存的目錄(一般是:安裝目錄\Data\Packages\User)了,我們可以建一個目錄pxtorem,也可以直接在開啟的目錄儲存。儲存為任何你喜歡的名字,關鍵是以.py為拓展名就可以了(你知道的,sublime text用的是python來寫的),我們這裡命名為text.py。儲存好了,現在我們要運行sublime text 給我們的哪個初始化外掛程式例子啦,輸入 ctrl+`開啟Sublime的控制台,它是一個可以訪問API的Python控制台。輸入下面的Python代碼來測試這個例子外掛程式:
view.run_command('example')
這個時候注意觀察當前的檔案開頭插入了“Hello,World”,當前檔案也變成待儲存的狀態,好了,測試成功,我們按ctrl+z,讓它回到開始的狀態的吧。等等,為什麼是“example”?它是從前面外掛程式例子裡 class ExampleCommand 來的,你需要換一個屬於你自己外掛程式的名字,把ExampleCommand裡的‘Example’改一下。這一改,然後有的人發現運行自己的外掛程式名稱運行不了了,原來這裡的設定有個規則,你用駝峰命名,例如PxToRemCommand 你啟動並執行時候需要是view.run_command('px_to_rem'),即用底線隔開,否則像例子那樣好了,開頭大寫後面全是小寫。第三步設定快速鍵每次都要輸入一下命令列,這個得煩死吧,我們先建立一個快速鍵吧,這個也是sublime text 所擅長的。在你外掛程式的目錄下,建立一個檔案,命名為Default (Windows).sublime-keymap然後內容為
[    {        "command": "px_to_rem",        "keys": [            "ctrl+alt+k"        ]    }]
這個快速鍵是 ctrl+alt+k,按下就會運行px_to_rem命令,相當與按下快速鍵執行view.run_command('px_to_rem'),你可以改成不會衝突的別的按鍵,試試看看生效了沒。第四步就是編寫程式1、從設定檔案裡讀取資訊,之前同事寫的是json格式的,很熟悉呀
{     "files": ["./test/style.css"],    "root_value": 20,    "unit_precision": 5,    "prop_white_list": ["width", "height", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left", "margin", "margin-top", "margin-right", "margin-bottom", "margin-left"],    "replace": false,    "media_query": false}
儲存。然後我們到之前我們建的外掛程式檔案text.py裡去試試看能不能擷取到我們的設定資訊。
import sublime, sublime_pluginSETTINGS_FILE = "px_to_rem.sublime-settings"class PxToRemCommand(sublime_plugin.TextCommand):     def run(self, edit):          #load config          settings = sublime.load_settings(SETTINGS_FILE)          #file          files = settings.get("files");          print files

我們先用sublime.load_settings()把設定檔案引入,然後用settings.get()去取我們想要的屬性。最後用print 列印到控制台。然後我們用crtl+`開啟控制台,然後我們運行我們的外掛程式ctrl+alt+k,看看列印出我們想要的東西沒。2、我們在設定檔案裡有一個白名單,只有這個白名單裡的屬性我們才會去更改它的值單位px為rem。取得設定檔案白名單
<pre name="code" class="python">prop_white_list = settings.get("prop_white_list",[])

然後去找當前檔案裡(樣式檔案)白名單裡的屬性,這個時候用到sublime text 介面self.view.find_all() 如下:
for text in prop_white_list:               matches[text] = self.view.find_all(text+r":(\s*(auto)?([+-]?\d*\.?\d+(px)?)?)+")

我這個正則寫得不太好的,汗。這裡取得了,sublime text編輯器裡的Region集合,就是匹配地區的集合。這個Region 有begin()和end()等方法。詳情看文檔。3、我們要把我們找到的地區集合裡的“數值px”替換成“數值rem”,先取得數值計算成跟相對與跟rem的值,然後再替換px為rem,開始我想用的是replace替換,不過python裡replace做不到,只能用的sub,匹配到值然後調用自己定義的函數replaceToRem處理,要用到replace要引入re這個庫,用到的一些數學方法要用到math,要在頁面頂部引入。
for text in prop_white_list:               for i in matches[text]:                    reStr = self.view.substr(i)                    replaced = re.sub("(?P<number>([+-]?)\d*\.?\d+)",replaceToRem,reStr)                    replaced = str(replaced).replace("px","rem")                    #self.view.replace(edit, i, replaced)                    print replaced                    self.view.insert(edit, i.end(), ";"+replaced)

其中的函數replaceToRem 如下:
def replaceToRem(replaceString):               #               intStr = replaceString.group("number")               intValue = float(intStr)               #               newValue = intValue / root_value               #               newValue = round(newValue,unit_precision)               newValueStr = str(newValue)               #               newValueStr = re.sub("\.[0]+$","",newValueStr)               return newValueStr
到這裡一個sublime text外掛程式算是差不多完成了。
第五步添加到設定菜單裡第六步發布後面兩步我就省略啦,可以參考這篇文章:http://www.welefen.com/how-to-develop-sublime-text-plugin.html 人家寫得不錯的。我寫這個文章就是想大家學會如何從設定檔案裡擷取設定,另外知道replace不能調用函數,而sub可以,最後sublime text不同版本的介面有一些有一點點的區別,sublime text的外掛程式還是很容易寫的,我幾乎不用sublime text也不會python也可以寫出來的哦。最後附上所有代碼:text.py檔案
import sublime, sublime_plugin, reimport mathSETTINGS_FILE = "px_to_rem.sublime-settings"class PxToRemCommand(sublime_plugin.TextCommand):     def run(self, edit):          #load config          settings = sublime.load_settings(SETTINGS_FILE)          #file          files = settings.get("files");          #get rootValue (int)          root_value = int(settings.get("root_value",20))          # toFixed the value (int)          unit_precision = int(settings.get("unit_precision",5))          #replace prop list (list)          prop_white_list = settings.get("prop_white_list",[])          # relpace or append to end          replace = settings.get("replace",True)          #          media_query = settings.get("media_query",True)          #self.view.insert(edit, 0, root_value)          #content = self.view.substr(sublime.Region(0,self.view.size()-1))          #          matches ={}          def replaceToRem(replaceString):               #               intStr = replaceString.group("number")               intValue = float(intStr)               #               newValue = intValue / root_value               #               newValue = round(newValue,unit_precision)               newValueStr = str(newValue)               #               newValueStr = re.sub("\.[0]+$","",newValueStr)               return newValueStr          for text in prop_white_list:               matches[text] = self.view.find_all(text+r":(\s*(auto)?([+-]?\d*\.?\d+(px)?)?)+")          for text in prop_white_list:               for i in matches[text]:                    reStr = self.view.substr(i)                    replaced = re.sub("(?P<number>([+-]?)\d*\.?\d+)",replaceToRem,reStr)                    replaced = str(replaced).replace("px","rem")                    #self.view.replace(edit, i, replaced)                    print replaced                    self.view.insert(edit, i.end(), ";"+replaced)          print matches          #self.view.insert(edit, 0, matches)

px_to_rem.sublime-settings檔案
{     "files": ["./test/style.css"],    "root_value": 20,    "unit_precision": 5,    "prop_white_list": ["width", "height", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left", "margin", "margin-top", "margin-right", "margin-bottom", "margin-left"],    "replace": false,    "media_query": false}

Default (Windows).sublime-keymap 檔案
[    {        "command": "px_to_rem",        "keys": [            "ctrl+alt+k"        ]    }]
Main.sublime-menu 檔案
[    {        "id": "view",        "children":        [            {                "caption": "pxToRem",                "id": "px-to-rem",                "command": "px_to_rem"            }        ]    }]






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.