Write a Sublime Text 2 plug-in (replace the px Unit in the CSS file with the rem Unit)

Source: Internet
Author: User
Tags sublime text editor

Write a Sublime Text 2 plug-in (replace the px Unit in the CSS file with the rem Unit)
Three years ago, I knew sublime text, but at that time, DW was quite cool. Some days later, I tried to make myself feel embarrassed. So I used vim and five pens for two years, recently, I think you can try such a good editor and change yourself and use it. However, due to work reasons, it seems more important to be easy. Recently, we have been working on some mobile pages, and the long-pressed QR code has a bug. In ios, the scaled long-pressed pages won't show the "recognize QR code. Therefore, you need to change the page size. Do not adjust the page size. In this case, it would be better to use the rem unit. My colleague previously developed a px to rem tool https://github.com/stormtea123/viewtorem. This can be done with his tools. I am so lazy, and I feel tired of giving this tool to others and talking to others. So I want to write a sublime text plug-in. A simple requirement: Change the px Unit in the CSS file to the rem unit.Step 1: Search BaiduI asked Baidu about everything. The result is the translation of the article "How to Create a Sublime Text 2 Plugin", which is not complete yet. If you don't know English, you have to cry. Of course there are also some gains: Sublime Text interface of the Chinese Document http://www.oschina.net/translate/sublime-text-plugin-api-reference and English documents: http://www.sublimetext.com/docs/2/api_reference.html. I didn't think there were differences in naming excuses for different versions of the editor. Top, well, I don't know where to remember to look at English.Step 2 set the plug-inFind the directory of the plug-in and open an initialized plug-in editing file through Tools> New Plugin.... The file contains the following content:

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

Press Ctrl + s to save the file. At this time, the computer will open the directory to be saved (generally: installation directory \ Data \ Packages \ User, we can create a directory pxtorem or store it directly in the opened directory. Save it as any name you like. The key is to use. py as the extension name (You know, sublime text is written in python). Here we name it text. py. Save it. Now we want to run the initialization plug-in example provided by sublime text. Enter ctrl + 'to open the Sublime console, which is a Python console that can access the API. Enter the following Python code to test the plug-in Example:
view.run_command('example')
At this time, observe that "Hello, World" is inserted at the beginning of the current file, and the current file is also in the state to be saved. Okay, the test is successful. Press ctrl + z, Let it go back to the starting state. Why is it "example "? It comes from the class ExampleCommand in the previous plug-in example. You need to change the name of your plug-inModify 'example 'in ExampleCommand. In this case, some people find that the plug-in name cannot be run. In the past, there was a rule for you to name the plug-in, for example, PxToRemCommand. view.run_command( 'Px_to_rem ' ), Which is separated by underscores (_). Otherwise, it will be as good as the example. It will start with uppercase and end with lowercase letters. Step 3: Set shortcutsEnter the command line every time. This is annoying. Let's create a shortcut key, which is also what sublime text is good. In the directory of your plug-in, create a new file named Default (Windows). sublime-keymap and
[    {        "command": "px_to_rem",        "keys": [            "ctrl+alt+k"        ]    }]
Press ctrl + alt + k to run the px_to_rem command. view.run_command( 'Px_to_rem ' ), You can change it to a button that does not conflict with each other. Try to see if it takes effect. Step 4: Compile the program 1. Read Information from the setup file. My colleagues wrote json format before. I am very familiar with it.
{     "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}
Save. Then, go to the plug-in file text. py we created to see if we can get our settings.
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

We first useSublime. load_settings () introduces the setting file and uses settings. get () to obtain the desired attribute. Print it to the console. Then we use crtl + 'to open the console, and then we run our plug-in ctrl + alt + k to see if we want something to print out. 2. We have a whitelist in the settings file. Only the attributes in the whitelist can be changed. The unit of px is rem. Get the set file whitelist
prop_white_list = settings.get("prop_white_list",[])

Then, find the attributes in the whitelist of the current file (Style File), and use the sublime text interface self. view. find_all () as follows:
for text in prop_white_list:               matches[text] = self.view.find_all(text+r":(\s*(auto)?([+-]?\d*\.?\d+(px)?)?)+")

I am not quite familiar with this regular expression, Khan. The Region set in the sublime text editor is the set of matching regions. This Region has methods such as begin () and end. For more information, see the document. 3. We need to replace "numeric px" in the region set we have found with "numerical rem", and first obtain the value to calculate the relative and rem values, replace px with rem. At first, I want to replace it with replace. However, replace cannot be used in python. Only sub can be used to match the value and then replaceToRem can be called to process it, to use replace, we need to introduce the re library. math is used for some mathematical methods and should be introduced at the top of the page.
for text in prop_white_list:               for i in matches[text]:                    reStr = self.view.substr(i)                    replaced = re.sub("(?P
  
   ([+-]?)\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)
  

The replaceToRem function is as follows:
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
Here, a sublime text plug-in is almost complete.
Step 5 add to the settings menuStep 6 releaseI will omit the next two steps, you can refer to this article: http://www.welefen.com/how-to-develop-sublime-text-plugin.html people write well. I am writing this article to learn how to get settings from the setting file. Besides, I know that replace cannot call functions, but sub can, at last, there are some differences between sublime text interfaces of different versions. The sublime text plug-in is still easy to write. I almost don't need sublime text or can write it out in python. The following code is attached: text. py file.
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
  
   ([+-]?)\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
{     "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 File
[    {        "command": "px_to_rem",        "keys": [            "ctrl+alt+k"        ]    }]
Main. sublime-menu file
[    {        "id": "view",        "children":        [            {                "caption": "pxToRem",                "id": "px-to-rem",                "command": "px_to_rem"            }        ]    }]






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.