Home Download Buy Blog Forum Support

Soft tabs, selection wrap and switch syntax

Soft tabs, selection wrap and switch syntax

Postby iamntz on Sun May 15, 2011 7:36 pm

Hi guys. I'm new to Sublime (former E user) and I'm trying to add to Sublime features that I had in E.

Soft Tabs
First thing that was annoying to me was the soft tabs. I tried to mess with all settings but with no luck.
So i made this custom shortcut/key bind:
Code: Select all
   { "keys": ["tab"], "command": "move", "args": { "by": "words", "forward": true }, "context":[
      {   "key":    "following_text", "operator": "regex_contains", "operand": "^\\t", "match_all":true }
   ]}

(sublime-keymap)

Selection Wrap
I found there was a package with a lot of stuff that had this thing too, but was for Sublime 1. So i made this key bind:
Code: Select all
   {
      "keys"      :   ["alt+shift+w"],
      "command"   :   "insert_snippet",
      "args"   :   {
         "contents": "<${1:p}>${0:$SELECTION}</${1/\\s.*//}>"
      }
   }

Tada! Works! :)

Switch Syntax

this is the initial version, read below

This is kind of tricky. It may be a shorter version for this, but i didn't get it how to do it. All i found was this. Unfortunately, I didn't understand too much from that thing and what should i do with it. I was stuck at this:
Code: Select all
{ "keys": ["alt+1"], "command": "set_file_type", "args":{ ***** } }

With no clue on what should i put where astericses are.

So i did this keybinds:

Code: Select all
   { "keys": ["alt+1"], "command": "set_js_syntax" },
   { "keys": ["alt+2"], "command": "set_html_syntax" },
   { "keys": ["alt+3"], "command": "set_php_syntax" },
   { "keys": ["alt+4"], "command": "set_css_syntax" }

And for all syntax i created a new plugin that contains this:
Code: Select all
import sublime, sublime_plugin

class set_css_syntax(sublime_plugin.TextCommand):
   def run(self, edit):
      self.view.settings().set('syntax', 'Packages/CSS/CSS.tmLanguage')



Updated (10x to jbjornson)
Code: Select all
   { "keys": ["alt+1"], "command": "set_file_type", "args":{ "syntax" : "Packages/JavaScript/JavaScript.tmLanguage" } },
   { "keys": ["alt+2"], "command": "set_file_type", "args":{ "syntax" : "Packages/HTML/HTML.tmLanguage" } },
   { "keys": ["alt+3"], "command": "set_file_type", "args":{ "syntax" : "Packages/PHP/PHP.tmLanguage" } },
   { "keys": ["alt+4"], "command": "set_file_type", "args":{ "syntax" : "Packages/CSS/CSS.tmLanguage" } },


(you can replace CSS with any syntax you want)

So, what do you think guys? :D

The only two thing that I need to replace E completely is: translate all snippets from E to ST and make ctrl+tab to behave (is very redundant right now). Go to last active tab would be great. Any clues?
(oh, and a history tree would be nice to have)
Last edited by iamntz on Thu Jul 07, 2011 11:33 am, edited 3 times in total.
iamntz
 
Posts: 905
Joined: Fri Apr 29, 2011 8:52 am
Location: Romania

Re: Soft tabs, selection wrap and switch syntax

Postby jbjornson on Mon May 16, 2011 9:26 am

I like the "switch syntax" idea, but I'm not sure that having so many similar plugins is ideal. How about this instead (see below)? It also allows for the user to choose a syntax if one isn't defined in the shortcut. Ideally (in the future), we could have access to the quick panel API and present a filterable list of syntaxes to choose from (if one isn't defined in the shortcut).

Code: Select all
import sublime, sublime_plugin, os, fnmatch

class SetFileSyntaxCommand(sublime_plugin.TextCommand):

    def run(self, edit, syntax=''):
        """Set the syntax for this view as specified, or, if not specified, ask the user for the syntax type to change to"""
        self.populate_map()
        if not syntax in syntaxMap:
            message = 'Please type the name of the syntax type to switch the view to: '
            sublime.active_window().show_input_panel(message, 'java', lambda s: self.set_syntax(s), None, None)
        else:
            self.set_syntax(syntax)

    def set_syntax(self, syntax):
        """Set the syntax for this view if it matches a key in the map"""
        syntax = syntax.lower()
        if syntax in syntaxMap:
            self.view.settings().set('syntax', syntaxMap[syntax])

    def populate_map(self):
        """Get a list of valid syntax highlighting options"""
        if not hasattr(self, 'syntaxMap'):
            self.syntaxMap = {}
            for root, dirnames, filenames in os.walk(sublime.packages_path()):
                for filename in fnmatch.filter(filenames, '*.tmLanguage'):
                    name = os.path.splitext(filename)[0].lower()
                    full_path = os.path.join(root, filename)
                    relative_path = full_path.replace(sublime.packages_path(), 'Packages')
                    self.syntaxMap[name] = relative_path


You could then setup your shortcuts as follows:

Code: Select all
   { "keys": ["alt+1"], "command": "set_file_syntax", "args": {"syntax": "javascript"}},
   { "keys": ["alt+2"], "command": "set_file_syntax", "args": {"syntax": "html"}},
   { "keys": ["alt+3"], "command": "set_file_syntax", "args": {"syntax": "php"}},
   { "keys": ["alt+4"], "command": "set_file_syntax", "args": {"syntax": "css"}}
jbjornson
 
Posts: 345
Joined: Tue Oct 27, 2009 4:25 pm
Location: Zurich, Switzerland

Re: Soft tabs, selection wrap and switch syntax

Postby iamntz on Mon May 16, 2011 11:25 am

I know that plugin work around is not a good idea, but I kind of needed something that... works. And the json thing didn't worked for me (doesn't work with your code either).

And about your code: my py skillz are zero. On my ... plugins i was sort of a code monkey :D

Wondering if is possible to add a selector for each key bind, like so:
Image
iamntz
 
Posts: 905
Joined: Fri Apr 29, 2011 8:52 am
Location: Romania

Re: Soft tabs, selection wrap and switch syntax

Postby jbjornson on Mon May 16, 2011 2:24 pm

Ok, try this updated version. If it doesn't work have a look in the console for error messages, etc...

Code: Select all
import sublime, sublime_plugin, os, fnmatch

class SetFileSyntaxCommand(sublime_plugin.TextCommand):

    def run(self, edit, syntax=''):
        """Set the syntax for this view as specified, or, if not specified, ask the user for the syntax type to change to"""
        self.populate_map()
        if not syntax in self.syntaxMap:
            message = 'Please type the name of the syntax type to switch the view to: '
            sublime.active_window().show_input_panel(message, self.get_current_syntax(), lambda s: self.set_syntax(s), None, None)
        else:
            self.set_syntax(syntax)

    def set_syntax(self, syntax):
        """Set the syntax for this view if it matches a key in the map"""
        if syntax in self.syntaxMap:
            self.view.set_syntax_file(self.syntaxMap[syntax.lower()])
        else:
            print '"%s" is not a known syntax highlighting' % (syntax)
            print self.syntaxMap

    def populate_map(self):
        """Get a list of valid syntax highlighting options"""
        # if not hasattr(self, 'syntaxMap'):
        self.syntaxMap = {}
        for root, dirnames, filenames in os.walk(sublime.packages_path()):
            for filename in fnmatch.filter(filenames, '*.tmLanguage'):
                name = os.path.splitext(filename)[0]
                full_path = os.path.join(root, filename)
                relative_path = full_path.replace(sublime.packages_path(), 'Packages')
                relative_path = relative_path.replace('\\', '/') # fix windows paths
                self.syntaxMap[name.lower()] = relative_path
                print 'Syntax: %-20s -> "%s" (%s)' % (name, relative_path, full_path)

    def get_current_syntax(self):
        current_syntax = self.view.settings().get('syntax')
        (path, filename) = os.path.split(current_syntax)
        (shortname, extension) = os.path.splitext(filename)
        return shortname


By the way, these key mappings work for me:

Code: Select all
    { "keys": ["alt+1"], "command": "set_file_type", "args":{ "syntax" : "Packages/Java/Java.tmLanguage" } },
    { "keys": ["alt+2"], "command": "set_file_type", "args":{ "syntax" : "Packages/Python/Python.tmLanguage" } },


On Windows at least, it looks like the above doesn't work if you use backslashes (\), but it works fine if you use (unix style) forward slashes. Maybe your key-mappings weren't working because you were using backslashes?

As a side note, "alt+1".."alt+0" are mapped by default to quickly switch between views so if you want that functionality you may want to change your key mappings.
jbjornson
 
Posts: 345
Joined: Tue Oct 27, 2009 4:25 pm
Location: Zurich, Switzerland

Re: Soft tabs, selection wrap and switch syntax

Postby iamntz on Mon May 16, 2011 2:58 pm

YES! It works. Great, thanks!

Unfortunately, i didn't fully understand how to call custom plugins. I saw there are plugins named in a way, saved with another name and called with a totally different name. How is this possible? :shock:
iamntz
 
Posts: 905
Joined: Fri Apr 29, 2011 8:52 am
Location: Romania

Re: Soft tabs, selection wrap and switch syntax

Postby jbjornson on Tue May 17, 2011 8:43 am

Sublime Text converts camel-case plugin names (eg SetFileSyntaxCommand), removed the "Command" at the end and separates the capitalized words with underscores. So in this case, "SetFileSyntaxCommand" becomes "set_file_syntax".

From the "Conventions for Command Names" section in the documentation (http://sublimetext.info/docs/reference/plugins.html):

Sublime Text 2 command class names are suffixed by convention with Command and written as CamelCasedPhrases.

However, Sublime Text 2 transforms the class name from CamelCasedPhrases to camel_cased_phrases. So ExampleCommand would turn into example and AnotherExampleCommand would turn into another_example.

For class definition names, use CamelCasedPhrasesCommand; to call a command from the API, use the transformed name (camel_cased_phrases).
jbjornson
 
Posts: 345
Joined: Tue Oct 27, 2009 4:25 pm
Location: Zurich, Switzerland

Re: Soft tabs, selection wrap and switch syntax

Postby iamntz on Tue May 17, 2011 10:52 am

Sweet! Now make a lot of sense.

Thanks!
iamntz
 
Posts: 905
Joined: Fri Apr 29, 2011 8:52 am
Location: Romania

Re: Soft tabs, selection wrap and switch syntax

Postby rolandba on Tue May 17, 2011 6:57 pm

Thank you really much, very usefull extensions.
rolandba
 
Posts: 4
Joined: Fri Mar 11, 2011 12:25 pm

Re: Soft tabs, selection wrap and switch syntax

Postby jbjornson on Wed Jun 22, 2011 1:38 pm

...an updated version using the quick panel introduced in build 2069:

Code: Select all
import sublime, sublime_plugin, os, fnmatch

class SetFileSyntaxCommand(sublime_plugin.WindowCommand):
    def callback(self, index):
        if index >= 0:
            self.window.active_view().set_syntax_file(self.syntaxList[index][1])

    def run(self):
        self.populate_map()
        self.window.show_quick_panel(self.syntaxList, self.callback)

    def populate_map(self):
        """Get a list of valid syntax highlighting options"""
        self.syntaxList = []
        for root, dirnames, filenames in os.walk(sublime.packages_path()):
            for filename in fnmatch.filter(filenames, '*.tmLanguage'):
                name = os.path.splitext(filename)[0]
                full_path = os.path.join(root, filename)
                relative_path = full_path.replace(sublime.packages_path(), 'Packages')
                relative_path = relative_path.replace('\\', '/') # fix windows paths

                self.syntaxList.append([name, relative_path])


Updated callback to correctly handle no highlight being selected
Last edited by jbjornson on Wed Jun 22, 2011 1:58 pm, edited 1 time in total.
jbjornson
 
Posts: 345
Joined: Tue Oct 27, 2009 4:25 pm
Location: Zurich, Switzerland

Re: Soft tabs, selection wrap and switch syntax

Postby bizoo on Wed Jun 22, 2011 1:57 pm

Isn't it redundant with the new Command Palette ?

I tried this key binding:
Code: Select all
[
    { "keys": ["ctrl+shift+y"], "command": "show_overlay", "args": {"overlay": "command_palette", "text": "Set Syntax:"} }
]

but it doesn't work properly, look like the "text" parameter is ignored. Maybe Jon could make it work.
bizoo
 
Posts: 874
Joined: Wed Dec 08, 2010 6:53 am
Location: Switzerland

Next

Return to Plugin Announcements

Who is online

Users browsing this forum: Google [Bot] and 9 guests