Sublime Forum

Insert Open/Close Tag (With Current Word)

#1

I use this HTML key mapping constantly in TextMate (control-less-than) and it’s sorely missed. Is there a way to implement this functionality via custom key mappings in ST2?

0 Likes

#2

Still hoping someone knows a solution for this.

0 Likes

#3

If you could better explain the behavior of “Insert Open/Close Tag (With Current Word)”, I might be able to help. I’m not a textmate user, so I’m unfamiliar with the command.

0 Likes

#4
word[/code] becomes [code]<word></word>
0 Likes

#5

Create a file InsertAsTag.py in your Users folder with this content:

[code]import sublime
import sublime_plugin

class InsertAsTagCommand(sublime_plugin.TextCommand):

def run(self, edit):

    for region in self.view.sel():
        word_reg = self.view.word(region)
        word = self.view.substr(word_reg)
        s = "<%s></%s>" % (word, word)
        self.view.replace(edit, word_reg, s)[/code]

and ad this to your User-Key-Bindings:

{ "keys": "ctrl+<"], "command": "insert_as_tag"}
0 Likes

#6

Thanks! I only got partway there using a snippet, because the original text would remain and I couldn’t figure out how to remove it. I was using the following:

<$TM_CURRENT_WORD>$1</$TM_CURRENT_WORD>

The only thing I had to do differently to get the command working was to use the following in my keybindings. I’m on OS X if that makes a difference.

{ "keys": "ctrl+shift+,"], "command": "insert_as_tag"}
0 Likes

#7

Awesome! Thanks very much! :smiley:

Edit: Could it be edited so that the cursor ends up between the tags afterward?

Edit 2: Here is the implementation of this command in TextMate: gist.github.com/1539035

0 Likes

#8

This should do it

[code]import sublime
import sublime_plugin

class InsertAsTagCommand(sublime_plugin.TextCommand):

def run(self, edit):

    for region in self.view.sel():
        self.view.sel().clear()
        word_reg = self.view.word(region)
        word = self.view.substr(word_reg)
        s = "<%s></%s>" % (word, word)
        self.view.replace(edit, word_reg, s)
        self.view.sel().clear()
        if region.a < region.b:
              self.view.sel().add(sublime.Region(region.b + 2))
        else:
              self.view.sel().add(sublime.Region(region.a + 2))
        self.view.show(self.view.sel())[/code]

However, have you installed the zenCoding plugin? It makes this stuff pretty much obsolete.

Edit: It also works if the cursor is at the end of the word, it doesn’t have to be selected.

0 Likes

#9

Thanks again! I modified it to default to a paragraph tag if there’s no current word. github.com/jimmycuadra/sublime- … rtAsTag.py

0 Likes

#10

This is the type of command that are very welcome to become part of the Tag Package.
github.com/SublimeText/Tag “Collection of packages about HTML/XML tags.”

Feel free to submit or request the addition.

Regards,

0 Likes

#11

This is now part of the “Tag” Package (https://github.com/SublimeText/Tag).

0 Likes