Skip to content

Instantly share code, notes, and snippets.

@kihlstrom
Created August 9, 2011 13:04
Show Gist options
  • Save kihlstrom/1133984 to your computer and use it in GitHub Desktop.
Save kihlstrom/1133984 to your computer and use it in GitHub Desktop.
Close Tag On Slash Command for Sublime Text 2
import sublime, sublime_plugin
class CloseTagOnSlashCommand( sublime_plugin.TextCommand ) :
def run( self, edit ) :
self.view.insert( edit, self.view.sel()[0].begin(), '/' )
whatIsLeft = self.view.substr( sublime.Region( 0, self.view.sel()[0].begin() ) )
if whatIsLeft[-2] == '<' :
tag = ''
while len( tag ) == 0 and len( whatIsLeft ) > 0 :
closeStart = whatIsLeft.rfind( '</' )
if closeStart >= 0 :
closeEnd = whatIsLeft.find( '>', closeStart + 1 )
if closeEnd >= 0 :
tag = self.lastOpenTag( whatIsLeft[closeEnd:] )
if len( tag ) == 0 :
openStart = whatIsLeft.rfind( '<' + whatIsLeft[closeStart + 2:closeEnd] + '>' )
if openStart == -1 :
openStart = whatIsLeft.rfind( '<' + whatIsLeft[closeStart + 2:closeEnd] + ' ' )
if openStart > 0 :
whatIsLeft = whatIsLeft[0:openStart]
else :
whatIsLeft = ''
whatIsLeft = whatIsLeft[0:closeStart]
else :
whatIsLeft = ''
if len( tag ) > 0 :
self.view.insert( edit, self.view.sel()[0].begin(), tag + '>' )
def lastOpenTag( self, string ) :
tag = ''
tagEnd = string.rfind( '>' )
if ( tagEnd > 1 ) and ( string[tagEnd - 1] != '/' ) :
tagStart = string.rfind( '<', 0, tagEnd - 1 )
if tagStart >= 0 and ( string[tagStart + 1] != '/' ) :
tag = string[( tagStart + 1 ):tagEnd].split( ' ', 1 )[0]
return tag
@kihlstrom
Copy link
Author

While in Sumblime Text 2 select Tools > New Plugin... from the main menu and paste the code, save as close_tag_on_slash.py, then add the following keymap

[
{ "keys": ["/"], "command": "close_tag_on_slash" }
]

@kihlstrom
Copy link
Author

For a better working solution please have a look at http://github.com/wastek/Close-Tag-On-Slash-for-Sublime-Text instead...

@kihlstrom
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment