Search code examples
code-snippetssublimetext

Fill line up with special Character before and after Text


I would like to create a Sublime Text 2 Snippet that fills up the space before and after the Variable I type with spaces.

It should look like this:

===========================my_filename.js===========================

The Filename should be centered so the number of spaces before and after the Text have to match. Also I need the overall column width of this line the stay the same. So when I add 2 Characters the number of spaces on each side gets reduced by one.

I think a sample for this would be:

spacesLeft  = roundDown((columnWidth/2) - (textSize/2))
spacesRight = roundUp((columnWidth/2) - (textSize/2))

But since only RegEx is available in Sublime Snippets I don't see me able, to accomplish this task.

Could Vintagmode help me in any Way?

Thanks for your help!


Solution

  • Because snippets are essentially static, they wouldn't be able to help you in this case. However, you could create a plugin to do this relatively easily. Sublime Text uses python for its plugins. You can create one by going to Tools > New Plugin. ST2's API can be found here and is very impressive. Essentially, you'll want to store the current selection (your variable) using

    sel_reg = self.view.sel()[0] # the current selection 'Region'
    sel = self.view.substr(sel_reg) # the text within the 'Region'
    

    Then generate the ='s

    signs = ''
    each_side = len(80 - len(sel))/2 # 80 is the standard window length, 
                                       # change this to what you want.
                                       # Not sure about how to make it dynamic.
    for x in xrange(each_side):
      signs += '='
    

    Then replace the current line (self.view.line(sel)) with signs + sel + signs.