Skip to content

Instantly share code, notes, and snippets.

@wortwart
Created July 16, 2015 08:32
Show Gist options
  • Save wortwart/9778c13408711b4e419c to your computer and use it in GitHub Desktop.
Save wortwart/9778c13408711b4e419c to your computer and use it in GitHub Desktop.
Sublime Text plugin to insert a tag
import sublime, sublime_plugin
def get_tab_size(view):
return int(view.settings().get('tab_size', 8))
def normed_indentation_pt(view, sel, non_space=False):
tab_size = get_tab_size(view)
pos = 0
ln = view.line(sel)
for pt in range(ln.begin(), ln.end() if non_space else sel.begin()):
ch = view.substr(pt)
if ch == '\t':
pos += tab_size - (pos % tab_size)
elif ch.isspace():
pos += 1
elif non_space:
break
else:
pos+=1
return pos
def line_and_normed_pt(view, pt):
return ( view.rowcol(pt)[0],
normed_indentation_pt(view, sublime.Region(pt)) )
def pt_from_line_and_normed_pt(view, p, insertLength=0):
ln, pt = p
pt += insertLength
i = start_pt = view.text_point(ln, 0)
tab_size = get_tab_size(view)
pos = 0
for i in range(start_pt, start_pt + pt):
ch = view.substr(i)
if ch == '\t':
pos += tab_size - (pos % tab_size)
else:
pos += 1
i += 1
if pos == pt: break
return i
def save_selections(view, selections=None):
return [ [line_and_normed_pt(view, p) for p in (sel.a, sel.b)]
for sel in selections or view.sel() ]
def region_from_stored_selection(view, stored, insertLength):
return sublime.Region(*[pt_from_line_and_normed_pt(view, p, insertLength) for p in stored])
def restore_selections(view, lines_and_pts, insertLength):
view.sel().clear()
for stored in lines_and_pts:
view.sel().add(region_from_stored_selection(view, stored, insertLength))
class insertMyTagCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
sels = save_selections(view)
for sel in view.sel():
sel.start = sel.a if (sel.a < sel.b) else sel.b
sel.end = sel.b if (sel.a < sel.b) else sel.a
insert1Length = view.insert(edit, sel.start, '<MYTAG>')
view.insert(edit, sel.end + insert1Length, '</MYTAG>')
restore_selections(view, sels, insert1Length)
@wortwart
Copy link
Author

Creates tags on cursor position or wraps them around selected text. A lot of overhead lifted from the default plugin indentation.py just to move the cursor between the tags after inserting them (if you know better how to do that please tell me).

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